stormcloud-video-player 0.7.50 → 0.8.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +269 -228
- package/dist/stormcloud-vp.min.js +1 -1
- package/lib/index.cjs +5197 -6747
- package/lib/index.cjs.map +1 -1
- package/lib/index.d.cts +196 -195
- package/lib/index.d.ts +196 -195
- package/lib/index.js +5321 -6863
- package/lib/index.js.map +1 -1
- package/lib/player/StormcloudVideoPlayer.cjs +4802 -3170
- package/lib/player/StormcloudVideoPlayer.cjs.map +1 -1
- package/lib/player/StormcloudVideoPlayer.d.cts +113 -70
- package/lib/players/HlsPlayer.cjs +4810 -3179
- package/lib/players/HlsPlayer.cjs.map +1 -1
- package/lib/players/HlsPlayer.d.cts +1 -1
- package/lib/players/index.cjs +4877 -3246
- package/lib/players/index.cjs.map +1 -1
- package/lib/sdk/hlsAdPlayer.cjs +1021 -0
- package/lib/sdk/hlsAdPlayer.cjs.map +1 -0
- package/lib/sdk/hlsAdPlayer.d.cts +10 -0
- package/lib/sdk/pal.cjs +358 -0
- package/lib/sdk/pal.cjs.map +1 -0
- package/lib/sdk/pal.d.cts +28 -0
- package/lib/{types-CIHDHY7A.d.cts → types-DDwAfBLt.d.cts} +11 -10
- package/lib/ui/StormcloudVideoPlayer.cjs +5070 -6609
- package/lib/ui/StormcloudVideoPlayer.cjs.map +1 -1
- package/lib/ui/StormcloudVideoPlayer.d.cts +1 -14
- package/lib/utils/browserCompat.cjs +10 -114
- package/lib/utils/browserCompat.cjs.map +1 -1
- package/lib/utils/browserCompat.d.cts +3 -7
- package/lib/utils/tracking.cjs +179 -150
- package/lib/utils/tracking.cjs.map +1 -1
- package/lib/utils/tracking.d.cts +11 -6
- package/package.json +1 -2
- package/lib/sdk/adstormPlayer.cjs +0 -1567
- package/lib/sdk/adstormPlayer.cjs.map +0 -1
- package/lib/sdk/adstormPlayer.d.cts +0 -23
- package/lib/sdk/vastParser.cjs +0 -517
- package/lib/sdk/vastParser.cjs.map +0 -1
- package/lib/sdk/vastParser.d.cts +0 -45
- package/lib/ui/OverlayRenderer.cjs +0 -2376
- package/lib/ui/OverlayRenderer.cjs.map +0 -1
- package/lib/ui/OverlayRenderer.d.cts +0 -17
- package/lib/utils/adcision.cjs +0 -282
- package/lib/utils/adcision.cjs.map +0 -1
- package/lib/utils/adcision.d.cts +0 -31
- package/lib/utils/overlays.cjs +0 -354
- package/lib/utils/overlays.cjs.map +0 -1
- package/lib/utils/overlays.d.cts +0 -70
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["/home/ubuntu24-new/Dev/stormcloud-vp/lib/ui/StormcloudVideoPlayer.cjs","../../src/ui/StormcloudVideoPlayer.tsx","../../src/player/StormcloudVideoPlayer.ts","../../src/sdk/vastParser.ts","../../src/sdk/adstormPlayer.ts","../../src/utils/tracking.ts","../../src/utils/polyfills.ts","../../src/utils/browserCompat.ts","../../src/ui/OverlayRenderer.tsx","../../src/utils/overlays.ts"],"names":["__create","Object","create","__defProp","defineProperty","__getOwnPropDesc","getOwnPropertyDescriptor","__getOwnPropNames","getOwnPropertyNames","__getProtoOf","getPrototypeOf","__hasOwnProp","prototype","hasOwnProperty","__export","target","all","name","get","enumerable","__copyProps","to","from","except","desc","key","call","__toESM","mod","isNodeMode","__esModule","value","__toCommonJS","StormcloudVideoPlayer_exports","StormcloudVideoPlayerComponent","exports","import_react","require","import_hls","firePixelWithRetry","url","retries","delayMs","logPrefix","attempt","fetch","method","mode","cache","keepalive","Promise","r","setTimeout","Math","pow","console","warn","fireTrackingPixels","urls","sessionId","length","forEach","trackingUrl","includes","catch","img","Image","onerror","src","log","error","SUPPORTED_VIDEO_EXTENSIONS","UNSUPPORTED_VIDEO_EXTENSIONS","REQUEST_TIMEOUT_MS","REQUEST_RETRY_BACKOFF_MS","AD_LAYER_Z_INDEX","COUNTDOWN_Z_INDEX","STALL_TIMEOUT_MS","lastDot","pathname","URL","lastIndexOf","slice","toLowerCase","ext","getFileExtension","indexOf","replace","isSupportedFormat","mimeType","isUnsupportedFormat","createAdStormPlayer","contentVideo","options","licenseKey","debug","channelId","adPlaying","originalMutedState","originalVolume","max","min","volume","listeners","Map","adVideoElement","adContainerEl","adCountdownEl","currentAd","destroyed","tornDown","continueLiveStreamDuringAds","adStallTimerId","adCountdownTimerId","adHideTimerId","lastCountdownSecond","adListenersBound","parentPositionOverridden","adHandlers","timeupdate","clearAdStallTimer","progress","currentTime","duration","trackingFired","firstQuartile","trackingUrls","midpoint","thirdQuartile","updateAdCountdown","playing","start","startAdCountdown","ended","complete","handleAdComplete","e","handleAdError","waiting","pause","volumechange","muted","mute","play","resume","impression","remainingSec","preloadSlots","args","emit","event","payload","set","Array","fn","clearTimeout","clearAdCountdownTimer","clearInterval","ceil","textContent","durationSec","currentTimeSec","setInterval","generateSessionId","Date","now","random","toString","bindAdEventListeners","addEventListener","unbindAdEventListeners","removeEventListener","teardownCurrentPlayback","removeAttribute","load","buildVastUrl","durationSeconds","baseUrl","params","URLSearchParams","String","parseVastXml","xmlString","ads","parser","DOMParser","xmlDoc","parseFromString","parserError","querySelector","adElements","querySelectorAll","adElement","adId","getAttribute","title","durationText","durationParts","split","parseInt","parseFloat","mediaFileElements","mediaFiles","mf","type","trim","width","height","bitrate","originalUrl","replaceFlvExtension","push","unmute","el","eventKey","clickThrough","id","selectBestMediaFile","mp4Files","filter","candidates","targetWidth","videoWidth","targetHeight","videoHeight","sort","a","b","diffA","abs","diffB","createAdVideoElement","video","document","createElement","style","position","left","top","objectFit","backgroundColor","zIndex","playsInline","preload","setAdPlayingFlag","isPlaying","dataset","stormcloudAdPlaying","setupAdEventListeners","opacity","display","pointerEvents","visibility","fetchVastOnce","vastUrl","controller","timeoutId","requestInit","response","xmlText","AbortController","abort","credentials","headers","Accept","referrerPolicy","signal","ok","Error","status","statusText","text","fetchVast","lastError","delay","REQUEST_MAX_RETRIES","resolve","getDurationSecondsFromContext","requestContext","ctx","remainingBreakSec","breakDurationSec","Number","isNaN","requestAdFromApi","ad","assignCurrentAd","initialize","parent","parentElement","computed","window","getComputedStyle","container","bottom","justifyContent","transition","isolation","countdown","padding","color","fontFamily","lineHeight","appendChild","requestAds","parsed","reject","mediaFile","offsetHeight","stop","paused","destroy","remove","removeChild","clear","updateOptions","opts","playAd","message","preloadAd","arg1","arg2","token","playPreloaded","slot","delete","hasPreloaded","has","cancelPreload","isAdPlaying","resize","on","listener","Set","add","off","updateOriginalMutedState","nextVolume","getOriginalMutedState","getOriginalVolume","setAdVolume","getAdVolume","showPlaceholder","right","alignItems","borderRadius","background","fontSize","hidePlaceholder","getClientInfo","screen","navigator","ua","userAgent","platform","vendor","maxTouchPoints","memory","deviceMemory","hardwareConcurrency","screenInfo","availWidth","availHeight","orientation","pixelDepth","deviceType","brand","os","model","isSmartTV","isAndroid","isWebView","isWebApp","webosMatch","match","tizenMatch","tvMatch","test","androidModelMatch","outerHeight","outerWidth","matchMedia","matches","standalone","angle","substring","domain","location","hostname","origin","path","cachedBrowserId","language","languages","join","cookieEnabled","doNotTrack","referrer","visibilityState","getBrowserID","clientInfo","fingerprintString","encodedData","utf8","buffer","i","hashBuffer","hashArray","hashHex","hash","char","fallbackHash","timestamp","JSON","stringify","crypto","subtle","digest","Uint8Array","TextEncoder","encode","unescape","encodeURIComponent","charCodeAt","map","padStart","padEnd","TRACK_URL","sendTrackRequest","body","json","sendInitialTracking","browserId","trackingData","sendAdLoadedTracking","adLoadedInfo","sendAdImpressionTracking","adImpressionInfo","sendHeartbeat","heartbeatData","toISOString","polyfillURLSearchParams","URLSearchParamsPolyfill","init","parseQueryString","append","query","cleanQuery","startsWith","param","decodedKey","safeDecodeURIComponent","decodedValue","str","decodeURIComponent","values","getAll","callback","parts","polyfillTextEncoder","TextEncoderPolyfill","encoding","charcode","polyfillPromiseFinally","finally","constructor","then","reason","polyfillObjectAssign","assign","sources","TypeError","nextSource","nextKey","polyfillArrayFrom","arrayLike","mapFn","thisArg","items","len","result","polyfillStringIncludes","pos","search","polyfillStringEndsWith","endsWith","polyfillStringStartsWith","getWebKitVersion","userAgentData","detectBrowser","getPlatform","version","majorVersion","isLegacyTV","supportsIMA","supportsModernJS","recommendedAdPlayer","webOSVersion","tizenVersion","chromeVersionNum","chromeVersion","getChromeVersion","webkitVersion","browser","StormcloudVideoPlayer","lastAdInsertionPoint","adLayerInitialized","supportsGoogleIMA","logBrowserInfo","getBrowserConfigOverrides","overrides","allowNativeHls","DEBUG_HISTORY_LIMIT","config","pendingNextAdBids","continuousFetchLoopPromise","inAdBreak","adPodQueue","lastHeartbeatTime","currentAdIndex","totalAdsInBreak","showAds","isLiveStream","nativeHlsMode","videoSrcProtection","bufferedSegmentsCount","shouldAutoplayAfterBuffering","hasInitialBufferCompleted","activeAdRequestToken","maxPlaceholderDurationMs","processedAdInsertionUpdatedAt","totalAdRequestsInBreak","maxTotalAdRequestsPerBreak","pendingAdBreak","consecutiveFailures","maxConsecutiveFailures","lastAdRequestTime","minAdRequestIntervalMs","backoffBaseMs","adRequestTimeoutMs","maxBackoffMs","MIN_AD_REMAINING_MS","adRequestMaxRetries","adRequestRetryBackoffMs","debugLogEntries","adInsertionDebugHistory","initializePolyfills","browserOverrides","videoElement","adTransitionGapMs","debugAdTiming","browserForAdLayer","isSinglePipeline","singlePipelineMode","adLayer","shouldContinueLiveStreamDuringAds","adRequest","context","disableAds","bidder","cpm","impId","creativeId","currency","attached","attach","isLive","adBehavior","mainHlsInstance","autoplay","hls","Hls","minSegments","minSegmentsBeforePlay","enableWorker","backBufferLength","liveDurationInfinity","lowLatencyMode","maxLiveSyncPlaybackRate","liveSyncDuration","maxBufferLength","maxMaxBufferLength","maxBufferSize","maxBufferHole","highBufferWatchdogPeriod","nudgeOffset","nudgeMaxRetry","startPosition","Events","MEDIA_ATTACHED","loadSource","MANIFEST_PARSED","_","data","level","levels","details","some","live","projectId","startAdInsertionPolling","LEVEL_LOADED","checkAdInsertionInManifest","FRAG_BUFFERED","_evt","err","FRAG_CHANGED","frag","updated_at","segmentName","segment_ts_name","fragmentMatchesSegment","offsetMs","offset_seconds","withPrefetch","pushAdInsertionDebug","offsetSeconds","detail","sn","clearAdInsertionOffsetTimer","adInsertionOffsetTimerId","handleAdStart","FRAG_PARSING_USERDATA","samples","sample","bytes","isSCTE35","segName","relurl","ERROR","fatal","ErrorTypes","NETWORK_ERROR","startLoad","MEDIA_ERROR","recoverMediaError","attachMedia","getAdSource","attachAdLayerEventListeners","source","adIndex","errorPayload","errorMessage","errorCode","code","vastErrorCode","cause","innerError","causeMessage","pushDebugLog","handleAdFailure","clearAdFailsafeTimer","clearAdRequestWatchdog","disableFiller","savedMutedStateBeforeAd","expectedAdBreakDurationMs","adStopTimerId","scheduleAdStopCountdown","getRemainingAdMs","stopFillerBreakTimer","hidePlaceholderLayer","isShowingPlaceholder","remaining","breakMuted","breakVolume","preloadedTokens","syncMainContentAudioWhenVisible","shift","remainingNow","showPlaceholderLayer","isInAdTransition","bids","freshBids","remainingFinal","continuousFetchingActive","startContinuousFetchLoop","handleAdPodComplete","ensureFillerVideo","fillerVideo","filler","loop","readyState","startFillerBreakTimer","durationMs","fillerBreakTimerId","initializeAdLayer","timeUpdateHandler","onTimeUpdate","emptiedHandler","wasPaused","shouldUseNativeHls","streamType","getStreamType","canNative","canPlayType","initializeTracking","heartbeatInterval","sendHeartbeatIfNeeded","getCurrentAdIndex","getTotalAdsInBreak","getRemainingAdSeconds","remainingMs","isFinite","MAX_SAFE_INTEGER","isShowingAds","isInAdBreak","setDisableAds","disabled","adLayerShowing","shouldShowNativeControls","showCustomControls","startAdPrefetch","fragmentSn","detectedAtFragmentSn","isFetching","fetchStartTime","runAdPrefetch","firstBids","durSec","adDurationSec","estimatedCount","firstToken","results","clearPendingAdBreak","prefetchTimerId","cancelAndClearPreloadedTokens","adInsertionPollingId","fetchAdInsertionPoint","stopAdInsertionPolling","resp","prevSegment","isNew","segmentChanged","updatedAt","channel_id","fragments","isArray","fragStart","fragDuration","isCurrentlyPlaying","rawOffsetMs","elapsedInFragMs","remainingOffsetMs","round","extractTsFilename","clean","rawUrl","runContinuousFetchLoop","backoffMs","prefetchContext","urgentNeedAd","elapsed","sleepMs","mult","adBreakDurationMs","state","adBreakToken","adVolume","currentAdBreakStartWallClockMs","startAdFailsafeTimer","startAdRequestWatchdog","showPlaceholderAndWaitForAds","stopContinuousFetching","tryNextAvailableAdWithRateLimit","backoffMultiplier","backoffDelay","effectiveMinInterval","timeSinceLastRequest","waitTime","tryNextAvailableAd","_retryCount","stillRemaining","checkInterval","maxChecks","floor","_currentTimeSec","clearAdStopTimer","ms","ensureAdStoppedByTimer","elapsedSinceStartMs","pendingAds","checkIntervalMs","maxExtensionMsConfig","maxAdBreakExtensionMs","adBreakCheckIntervalMs","maxExtensionMs","expectedDurationMs","overrunMs","shouldExtendAdBreak","restoredMuted","restoredVolume","hlsRef","savedMuted","savedVolume","videoRef","debugEnabled","tryPlay","onManifestParsedRestore","pipelineDelayMs","requestAnimationFrame","timeoutMs","adFailsafeTimeoutMs","adRequestWatchdogToken","adRequestWatchdogId","logAdState","failsafeMs","adFailsafeToken","adFailsafeTimerId","videoPaused","imaAdPlaying","extra","isAdCurrentlyMuted","category","timestampMs","getAdInsertionDebugLog","getDebugLogs","toggleMute","currentAdVolume","toggleFullscreen","fullscreenElement","requestFullscreen","exitFullscreen","isMuted","adMuted","setMuted","setVolume","clampedVolume","preservedVolume","getVolume","isFullscreen","getMinHlsResolution","minPixels","Infinity","pixels","getMaxHlsResolution","maxPixels","currentLevel","getCurrentHlsSegmentDurationMs","fallbackMs","levelCandidates","nextLoadLevel","loadLevel","levelIndex","targetDurationSec","partTarget","targetduration","clientWidth","normalizeSwirlOverlay","raw","o","sc","scroller_config","scrollerConfig","normalized","normalizeScrollerConfig","fetchProjectOverlays","apiBaseUrl","base","OVERLAY_API_BASE","row","resolveImageUrl","imageUrl","import_jsx_runtime","computeVideoDimensions","nativeWidth","nativeHeight","displayWidth","offsetWidth","displayHeight","videoAspect","displayAspect","renderWidth","renderHeight","offsetX","offsetY","overlay","image_url","jsx","userSelect","TextOverlay","content","fontWeight","textAlign","boxSizing","wordBreak","textShadow","parseRSSXml","maxItems","stripped","doc","item","description","pubDate","author","RSS_CACHE_TTL_MS","cachedFetchRSSItems","rssUrl","rssCache","cached","expiresAt","promise","fetchRSSItems","encoded","contents","useId","useState","rssItems","setRssItems","rssError","setRssError","cfg","rss_url","max_items","auto_refresh","updateInterval","update_interval","useEffect","use_custom_text","custom_text","cancelled","setRssLoading","autoRefresh","interval","separator_char","segments","show_title","show_description","toLocaleDateString","show_author","show_category","scrollSpeed","direction","scroll_speed","font_size","font_family","font_weight","text_color","background_color","background_opacity","border_radius","itemSpacing","item_spacing","label","labelColor","labelTextColor","label_color","accentColor","label_text_color","accent_color","show_accent_line","preset","sep","fullText","uid","isHorizontal","isReverse","animId","jsxs","Fragment","keyframes","flexDirection","bgOpacity","hexToRgb","bgColor","textColor","isEquitiesStrip","flexShrink","minHeight","gap","pad","alignSelf","maxWidth","children","letterSpacing","textTransform","whiteSpace","labelLine2","flex","overflow","minWidth","animation","willChange","copy","paddingRight","React","margin","seg","paddingBottom","exec","clock","m","totalSec","sourceClock","overlayId","initialSec","tick","current","seconds","size","liveClock","period","displayPeriod","displayClock","f","textOverflow","homeTeam","marginTop","homeScore","awayTeam","awayScore","sponsorText","sponsorImageUrl","borderTop","alt","LowerThirdOverlay","w","h","accentH","headline","subtitle","qrSide","qrUrl","ctaText","showSubtitle","scheduledTime","thumbW","thumbnailUrl","iconType","eventTitle","opt","marginLeft","odds","BreakingNewsOverlay","urgency","labelBg","targetTime","getTime","calcCountdownRemaining","expired","setRemaining","n","showDays","d","showHours","showMinutes","showSeconds","s","marginBottom","eventName","units","u","arr","ShapeOverlay","border","hex","num","FADE_DURATION_MS","ENTER_ANIMATION_ALIASES","fade","slide_from_left","slide_from_right","slide_from_top","slide_from_bottom","slide_left","slide_right","slide_up","slide_down","normalizeEnterAnimation","v","getEnterAnimation","flat","enter_animation"],"mappings":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C,cAAgB;KAChBC,kBAAmB;QACnBC,mCAAAA,4BAAAA;;QAAAA,QAAAA,aAAY,kCAAZA,UAAAA,8BAAAA,SAAAA,0BAAAA,kCAAY;YAAZA,IAAAA,CAAY,OAAZA;YACAC,IAAAA,OAAa,EAAA,CAAA,MAAA,KAAA,SAAA,CAAA,MAAA,EAAA;gBACbC,MAAU,CAAA;YACVC,UAAY;QACd;;QAJEH;QAAAA;;;iBAAAA,8BAAAA;gBAAAA;;;gBAAAA;sBAAAA;;;;IAMF,KAASI,EAAAA,sBAAwBC,CAAA;MAExBX;IAAP,QAAOA,6BAAAA,oBAAAA,GAAA,CAAwBW,EAAC,cAAzBX,wCAAAA,6BAA8B;AACvC,KAAA,CAAA,OAAA,OAAA,GAAA;IAEA,gCAAA,OAASY,kBAAkBlM,OAAA;KACzB,IAAMmM,OAAQnM,QACXoM,eAAA","sourcesContent":["\"use strict\";\nvar __create = Object.create;\nvar __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __getProtoOf = Object.getPrototypeOf;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(\n // If the importer is in node compatibility mode or this is not an ESM\n // file that has been converted to a CommonJS file using a Babel-\n // compatible transform (i.e. \"__esModule\" has not been set), then set\n // \"default\" to the CommonJS \"module.exports\" for node compatibility.\n isNodeMode || !mod || !mod.__esModule ? __defProp(target, \"default\", { value: mod, enumerable: true }) : target,\n mod\n));\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\n\n// src/ui/StormcloudVideoPlayer.tsx\nvar StormcloudVideoPlayer_exports = {};\n__export(StormcloudVideoPlayer_exports, {\n StormcloudVideoPlayerComponent: () => StormcloudVideoPlayerComponent\n});\nmodule.exports = __toCommonJS(StormcloudVideoPlayer_exports);\nvar import_react2 = __toESM(require(\"react\"), 1);\n\n// src/player/StormcloudVideoPlayer.ts\nvar import_hls = __toESM(require(\"hls.js\"), 1);\n\n// src/sdk/vastParser.ts\nasync function firePixelWithRetry(url, retries = 2, delayMs = 500, logPrefix = \"[VastParser]\") {\n for (let attempt = 0; attempt <= retries; attempt++) {\n try {\n await fetch(url, {\n method: \"GET\",\n mode: \"no-cors\",\n cache: \"no-cache\",\n keepalive: true\n });\n return;\n } catch {\n if (attempt < retries) {\n await new Promise((r) => setTimeout(r, delayMs * Math.pow(2, attempt)));\n } else {\n console.warn(`${logPrefix} Tracking pixel failed after ${retries + 1} attempts: ${url}`);\n }\n }\n }\n}\nfunction fireTrackingPixels(urls, sessionId, logPrefix = \"[VastParser]\") {\n if (!urls || urls.length === 0) return;\n urls.forEach((url) => {\n try {\n let trackingUrl = url;\n if (sessionId) {\n trackingUrl = `${trackingUrl}${trackingUrl.includes(\"?\") ? \"&\" : \"?\"}session_id=${sessionId}`;\n }\n if (typeof fetch !== \"undefined\") {\n firePixelWithRetry(trackingUrl, 2, 500, logPrefix).catch(() => {\n });\n } else {\n const img = new Image(1, 1);\n img.onerror = () => {\n };\n img.src = trackingUrl;\n }\n console.log(`${logPrefix} Fired tracking pixel: ${trackingUrl}`);\n } catch (error) {\n console.warn(`${logPrefix} Error firing tracking pixel:`, error);\n }\n });\n}\n\n// src/sdk/adstormPlayer.ts\nvar SUPPORTED_VIDEO_EXTENSIONS = [\".mp4\", \".webm\", \".ogg\", \".m3u8\", \".ts\"];\nvar UNSUPPORTED_VIDEO_EXTENSIONS = [\".flv\", \".f4v\", \".swf\", \".wmv\", \".avi\", \".mov\", \".mkv\"];\nvar REQUEST_TIMEOUT_MS = 5e3;\nvar REQUEST_MAX_RETRIES = 3;\nvar REQUEST_RETRY_BACKOFF_MS = 1500;\nvar AD_LAYER_Z_INDEX = \"30\";\nvar COUNTDOWN_Z_INDEX = \"31\";\nvar STALL_TIMEOUT_MS = 8e3;\nfunction getFileExtension(url) {\n try {\n const pathname = new URL(url, \"http://dummy\").pathname;\n const lastDot = pathname.lastIndexOf(\".\");\n if (lastDot === -1) return \"\";\n return pathname.slice(lastDot).toLowerCase();\n } catch {\n const lastDot = url.lastIndexOf(\".\");\n if (lastDot === -1) return \"\";\n const ext = url.slice(lastDot).split(/[?#]/)[0];\n return (ext || \"\").toLowerCase();\n }\n}\nfunction isUnsupportedFormat(url) {\n const ext = getFileExtension(url);\n return UNSUPPORTED_VIDEO_EXTENSIONS.indexOf(ext) !== -1;\n}\nfunction replaceFlvExtension(url) {\n const ext = getFileExtension(url);\n if (ext === \".flv\") {\n return url.replace(/\\.flv(\\?|$)/i, \".mp4$1\");\n }\n return url;\n}\nfunction isSupportedFormat(url, mimeType) {\n if (isUnsupportedFormat(url)) {\n return false;\n }\n const ext = getFileExtension(url);\n if (SUPPORTED_VIDEO_EXTENSIONS.indexOf(ext) !== -1) {\n return true;\n }\n if (ext === \"\" || ext === \".\") {\n return mimeType.includes(\"video/mp4\") || mimeType.includes(\"video/webm\") || mimeType.includes(\"m3u8\") || mimeType.includes(\"application/x-mpegurl\");\n }\n return false;\n}\nfunction createAdStormPlayer(contentVideo, options) {\n const { licenseKey, debug = false, channelId } = options;\n let adPlaying = false;\n let originalMutedState = false;\n let originalVolume = Math.max(0, Math.min(1, contentVideo.volume || 1));\n const listeners = /* @__PURE__ */ new Map();\n let adVideoElement;\n let adContainerEl;\n let adCountdownEl;\n let currentAd;\n let destroyed = false;\n let tornDown = false;\n let continueLiveStreamDuringAds = false;\n let sessionId;\n let adStallTimerId;\n let adCountdownTimerId;\n let adHideTimerId;\n let lastCountdownSecond = -1;\n let adListenersBound = false;\n let parentPositionOverridden = false;\n const adHandlers = {\n timeupdate: () => {\n if (!currentAd || !adVideoElement || destroyed || tornDown) return;\n const progress = adVideoElement.currentTime / currentAd.duration;\n if (progress >= 0.25 && !trackingFired.firstQuartile) {\n trackingFired.firstQuartile = true;\n fireTrackingPixels2(currentAd.trackingUrls.firstQuartile);\n }\n if (progress >= 0.5 && !trackingFired.midpoint) {\n trackingFired.midpoint = true;\n fireTrackingPixels2(currentAd.trackingUrls.midpoint);\n }\n if (progress >= 0.75 && !trackingFired.thirdQuartile) {\n trackingFired.thirdQuartile = true;\n fireTrackingPixels2(currentAd.trackingUrls.thirdQuartile);\n }\n updateAdCountdown();\n },\n playing: () => {\n clearAdStallTimer();\n if (!currentAd || trackingFired.start || destroyed || tornDown) return;\n trackingFired.start = true;\n fireTrackingPixels2(currentAd.trackingUrls.start);\n startAdCountdown();\n log(\"Ad started playing\");\n },\n ended: () => {\n if (!currentAd || trackingFired.complete || destroyed || tornDown) return;\n trackingFired.complete = true;\n fireTrackingPixels2(currentAd.trackingUrls.complete);\n log(\"Ad completed\");\n handleAdComplete();\n },\n error: (e) => {\n if (destroyed || tornDown) return;\n console.error(\"[AdStormPlayer] Ad video error:\", e);\n if (currentAd) fireTrackingPixels2(currentAd.trackingUrls.error);\n handleAdError();\n },\n waiting: () => {\n clearAdStallTimer();\n adStallTimerId = setTimeout(() => {\n adStallTimerId = void 0;\n if (!adPlaying || destroyed || tornDown) return;\n console.warn(\"[AdStormPlayer] Ad playback stalled too long\");\n handleAdError();\n }, STALL_TIMEOUT_MS);\n },\n volumechange: () => {\n if (!currentAd || !adVideoElement || destroyed || tornDown) return;\n if (adVideoElement.muted || adVideoElement.volume <= 0) {\n fireTrackingPixels2(currentAd.trackingUrls.mute);\n } else {\n fireTrackingPixels2(currentAd.trackingUrls.unmute);\n }\n },\n pause: () => {\n if (!currentAd || !adVideoElement || destroyed || tornDown) return;\n if (!adVideoElement.ended) {\n fireTrackingPixels2(currentAd.trackingUrls.pause);\n }\n },\n play: () => {\n if (!currentAd || !adVideoElement || destroyed || tornDown) return;\n if (adVideoElement.currentTime > 0) {\n fireTrackingPixels2(currentAd.trackingUrls.resume);\n }\n }\n };\n let trackingFired = {\n impression: false,\n start: false,\n firstQuartile: false,\n midpoint: false,\n thirdQuartile: false,\n complete: false\n };\n const preloadSlots = /* @__PURE__ */ new Map();\n function log(...args) {\n if (debug) {\n console.log(\"[AdStormPlayer]\", ...args);\n }\n }\n function emit(event, payload) {\n const set = listeners.get(event);\n if (!set) return;\n for (const fn of Array.from(set)) {\n try {\n fn(payload);\n } catch (error) {\n console.warn(`[AdStormPlayer] Error in event listener for ${event}:`, error);\n }\n }\n }\n function fireTrackingPixels2(urls) {\n fireTrackingPixels(urls, sessionId, \"[AdStormPlayer]\");\n }\n function clearAdStallTimer() {\n if (adStallTimerId) {\n clearTimeout(adStallTimerId);\n adStallTimerId = void 0;\n }\n }\n function clearAdCountdownTimer() {\n if (adCountdownTimerId) {\n clearInterval(adCountdownTimerId);\n adCountdownTimerId = void 0;\n }\n lastCountdownSecond = -1;\n }\n function updateAdCountdown() {\n if (!adCountdownEl || !adVideoElement || !currentAd || !adPlaying) return;\n const remainingSec = Math.max(\n 0,\n Math.ceil((currentAd.duration || 0) - adVideoElement.currentTime)\n );\n if (remainingSec === lastCountdownSecond) return;\n lastCountdownSecond = remainingSec;\n adCountdownEl.textContent = `Ad ${remainingSec}s`;\n emit(\"ad_countdown\", {\n remainingSec,\n durationSec: currentAd.duration,\n currentTimeSec: adVideoElement.currentTime\n });\n }\n function startAdCountdown() {\n clearAdCountdownTimer();\n updateAdCountdown();\n adCountdownTimerId = setInterval(updateAdCountdown, 250);\n }\n function generateSessionId() {\n return `adstorm-${Date.now()}-${Math.random().toString(36).slice(2, 10)}`;\n }\n function bindAdEventListeners() {\n if (!adVideoElement || adListenersBound) return;\n adVideoElement.addEventListener(\"timeupdate\", adHandlers.timeupdate);\n adVideoElement.addEventListener(\"playing\", adHandlers.playing);\n adVideoElement.addEventListener(\"ended\", adHandlers.ended);\n adVideoElement.addEventListener(\"error\", adHandlers.error);\n adVideoElement.addEventListener(\"waiting\", adHandlers.waiting);\n adVideoElement.addEventListener(\"volumechange\", adHandlers.volumechange);\n adVideoElement.addEventListener(\"pause\", adHandlers.pause);\n adVideoElement.addEventListener(\"play\", adHandlers.play);\n adListenersBound = true;\n }\n function unbindAdEventListeners() {\n if (!adVideoElement || !adListenersBound) return;\n adVideoElement.removeEventListener(\"timeupdate\", adHandlers.timeupdate);\n adVideoElement.removeEventListener(\"playing\", adHandlers.playing);\n adVideoElement.removeEventListener(\"ended\", adHandlers.ended);\n adVideoElement.removeEventListener(\"error\", adHandlers.error);\n adVideoElement.removeEventListener(\"waiting\", adHandlers.waiting);\n adVideoElement.removeEventListener(\"volumechange\", adHandlers.volumechange);\n adVideoElement.removeEventListener(\"pause\", adHandlers.pause);\n adVideoElement.removeEventListener(\"play\", adHandlers.play);\n adListenersBound = false;\n }\n function teardownCurrentPlayback() {\n unbindAdEventListeners();\n clearAdStallTimer();\n clearAdCountdownTimer();\n if (!adVideoElement) return;\n adVideoElement.pause();\n adVideoElement.removeAttribute(\"src\");\n adVideoElement.load();\n }\n function buildVastUrl(durationSeconds) {\n const baseUrl = `https://adstorm.co/api-adstorm-dev/adstorm/nab/vast/pod`;\n const params = new URLSearchParams();\n if (channelId != null) {\n params.set(\"channel_id\", String(channelId));\n }\n params.set(\"duration\", String(Math.ceil(durationSeconds)));\n return `${baseUrl}?${params.toString()}`;\n }\n function parseVastXml(xmlString) {\n const ads = [];\n try {\n const parser = new DOMParser();\n const xmlDoc = parser.parseFromString(xmlString, \"text/xml\");\n const parserError = xmlDoc.querySelector(\"parsererror\");\n if (parserError) {\n console.error(\"[AdStormPlayer] XML parsing error:\", parserError.textContent);\n return [];\n }\n const adElements = xmlDoc.querySelectorAll(\"Ad\");\n adElements.forEach((adElement) => {\n const adId = adElement.getAttribute(\"id\") || \"unknown\";\n const title = adElement.querySelector(\"AdTitle\")?.textContent || \"Ad\";\n const durationText = adElement.querySelector(\"Duration\")?.textContent || \"00:00:30\";\n const durationParts = durationText.split(\":\");\n const duration = parseInt(durationParts[0] || \"0\", 10) * 3600 + parseInt(durationParts[1] || \"0\", 10) * 60 + parseFloat(durationParts[2] || \"0\");\n const mediaFileElements = adElement.querySelectorAll(\"MediaFile\");\n const mediaFiles = [];\n mediaFileElements.forEach((mf) => {\n const type = mf.getAttribute(\"type\") || \"\";\n let url = mf.textContent?.trim() || \"\";\n const width = parseInt(mf.getAttribute(\"width\") || \"1920\", 10);\n const height = parseInt(mf.getAttribute(\"height\") || \"1080\", 10);\n const bitrate = mf.getAttribute(\"bitrate\") ? parseInt(mf.getAttribute(\"bitrate\"), 10) : void 0;\n if (!url) {\n log(`Skipping empty MediaFile URL`);\n return;\n }\n const originalUrl = url;\n url = replaceFlvExtension(url);\n if (url !== originalUrl) {\n log(`Converted FLV to MP4: ${originalUrl} -> ${url}`);\n }\n if (isUnsupportedFormat(url)) {\n const ext = getFileExtension(url);\n log(`Skipping unsupported format: ${url} (extension: ${ext}, declared type: ${type})`);\n return;\n }\n if (isSupportedFormat(url, type)) {\n mediaFiles.push({ url, type, width, height, bitrate });\n log(`Found media file: ${url} (${type}, ${width}x${height})`);\n } else {\n log(`Skipping incompatible media file: ${url} (type: ${type})`);\n }\n });\n if (mediaFiles.length === 0) {\n log(\"No valid media files found in ad:\", adId);\n return;\n }\n const trackingUrls = {\n impression: [],\n start: [],\n firstQuartile: [],\n midpoint: [],\n thirdQuartile: [],\n complete: [],\n mute: [],\n unmute: [],\n pause: [],\n resume: [],\n error: []\n };\n adElement.querySelectorAll(\"Impression\").forEach((el) => {\n const url = el.textContent?.trim();\n if (url) trackingUrls.impression.push(url);\n });\n adElement.querySelectorAll(\"Tracking\").forEach((el) => {\n const event = el.getAttribute(\"event\");\n const url = el.textContent?.trim();\n if (event && url) {\n const eventKey = event;\n if (trackingUrls[eventKey]) {\n trackingUrls[eventKey].push(url);\n }\n }\n });\n const clickThrough = adElement.querySelector(\"ClickThrough\")?.textContent?.trim();\n ads.push({\n id: adId,\n title,\n duration,\n mediaFiles,\n trackingUrls,\n clickThrough\n });\n log(`Parsed ad: ${title}, duration: ${duration}s, media files: ${mediaFiles.length}`);\n });\n } catch (error) {\n console.error(\"[AdStormPlayer] Error parsing VAST XML:\", error);\n }\n return ads;\n }\n function selectBestMediaFile(mediaFiles) {\n if (mediaFiles.length === 0) return null;\n if (mediaFiles.length === 1) return mediaFiles[0];\n const mp4Files = mediaFiles.filter((mf) => mf.type.includes(\"video/mp4\"));\n const candidates = mp4Files.length > 0 ? mp4Files : mediaFiles;\n const targetWidth = contentVideo.videoWidth || 1280;\n const targetHeight = contentVideo.videoHeight || 720;\n candidates.sort((a, b) => {\n const diffA = Math.abs(a.width - targetWidth) + Math.abs(a.height - targetHeight);\n const diffB = Math.abs(b.width - targetWidth) + Math.abs(b.height - targetHeight);\n return diffA - diffB;\n });\n return candidates[0] || null;\n }\n function createAdVideoElement() {\n const video = document.createElement(\"video\");\n video.style.position = \"absolute\";\n video.style.left = \"0\";\n video.style.top = \"0\";\n video.style.width = \"100%\";\n video.style.height = \"100%\";\n video.style.objectFit = \"contain\";\n video.style.backgroundColor = \"#000\";\n video.style.zIndex = \"1\";\n video.playsInline = true;\n video.preload = \"auto\";\n video.muted = originalMutedState;\n video.volume = originalMutedState ? 0 : originalVolume;\n return video;\n }\n function setAdPlayingFlag(isPlaying) {\n if (isPlaying) {\n contentVideo.dataset.stormcloudAdPlaying = \"true\";\n } else {\n delete contentVideo.dataset.stormcloudAdPlaying;\n }\n }\n function setupAdEventListeners() {\n bindAdEventListeners();\n }\n function handleAdComplete() {\n if (destroyed || tornDown) return;\n log(\"Handling ad completion\");\n adPlaying = false;\n setAdPlayingFlag(false);\n clearAdStallTimer();\n clearAdCountdownTimer();\n if (adContainerEl) {\n adContainerEl.style.opacity = \"0\";\n adHideTimerId = setTimeout(() => {\n if (adContainerEl) {\n adContainerEl.style.display = \"none\";\n adContainerEl.style.pointerEvents = \"none\";\n }\n }, 300);\n }\n contentVideo.style.visibility = \"visible\";\n contentVideo.style.opacity = \"1\";\n contentVideo.muted = originalMutedState;\n contentVideo.volume = originalVolume;\n currentAd = void 0;\n emit(\"content_resume\");\n emit(\"all_ads_completed\");\n }\n function handleAdError() {\n if (destroyed || tornDown) return;\n log(\"Handling ad error\");\n if (!adPlaying) return;\n adPlaying = false;\n setAdPlayingFlag(false);\n clearAdStallTimer();\n clearAdCountdownTimer();\n contentVideo.muted = originalMutedState;\n contentVideo.volume = originalVolume;\n contentVideo.style.visibility = \"visible\";\n contentVideo.style.opacity = \"1\";\n if (adContainerEl) {\n adContainerEl.style.display = \"none\";\n adContainerEl.style.pointerEvents = \"none\";\n }\n currentAd = void 0;\n emit(\"ad_error\");\n emit(\"content_resume\");\n }\n async function fetchVastOnce(durationSeconds) {\n const vastUrl = buildVastUrl(durationSeconds);\n log(\"Fetching VAST from:\", vastUrl);\n const controller = typeof AbortController !== \"undefined\" ? new AbortController() : null;\n const timeoutId = setTimeout(() => controller?.abort(), REQUEST_TIMEOUT_MS);\n try {\n const requestInit = {\n method: \"GET\",\n mode: \"cors\",\n credentials: \"omit\",\n headers: {\n Accept: \"application/xml, text/xml, */*\"\n },\n referrerPolicy: \"no-referrer-when-downgrade\"\n };\n if (controller) {\n requestInit.signal = controller.signal;\n }\n const response = await fetch(vastUrl, requestInit);\n if (!response.ok) {\n throw new Error(`Failed to fetch VAST: ${response.status} ${response.statusText}`);\n }\n const xmlText = await response.text();\n log(\"VAST response received, length:\", xmlText.length);\n return parseVastXml(xmlText);\n } finally {\n clearTimeout(timeoutId);\n }\n }\n async function fetchVast(durationSeconds) {\n let lastError;\n for (let attempt = 1; attempt <= REQUEST_MAX_RETRIES; attempt++) {\n try {\n const ads = await fetchVastOnce(durationSeconds);\n if (ads.length > 0) return ads;\n log(`No ad returned from VAST on attempt ${attempt}/${REQUEST_MAX_RETRIES}`);\n } catch (error) {\n lastError = error;\n if (error?.name === \"AbortError\") {\n console.warn(\n `[AdStormPlayer] VAST request timed out (${REQUEST_TIMEOUT_MS}ms), attempt ${attempt}/${REQUEST_MAX_RETRIES}`\n );\n } else {\n console.warn(`[AdStormPlayer] VAST request failed on attempt ${attempt}/${REQUEST_MAX_RETRIES}:`, error);\n }\n }\n if (attempt < REQUEST_MAX_RETRIES) {\n const delay = REQUEST_RETRY_BACKOFF_MS * attempt;\n await new Promise((resolve) => setTimeout(resolve, delay));\n }\n }\n if (lastError instanceof Error) {\n throw lastError;\n }\n return [];\n }\n function getDurationSecondsFromContext(requestContext) {\n if (!requestContext || typeof requestContext !== \"object\") {\n return 30;\n }\n const ctx = requestContext;\n const value = ctx.remainingBreakSec ?? ctx.breakDurationSec;\n if (typeof value !== \"number\" || Number.isNaN(value)) {\n return 30;\n }\n return Math.max(1, Math.ceil(value));\n }\n async function requestAdFromApi(requestContext) {\n const durationSeconds = getDurationSecondsFromContext(requestContext);\n const ads = await fetchVast(durationSeconds);\n return ads[0] || null;\n }\n function assignCurrentAd(ad) {\n currentAd = ad;\n sessionId = generateSessionId();\n trackingFired = {\n impression: false,\n start: false,\n firstQuartile: false,\n midpoint: false,\n thirdQuartile: false,\n complete: false\n };\n fireTrackingPixels2(currentAd.trackingUrls.impression);\n trackingFired.impression = true;\n emit(\"ad_impression\");\n }\n return {\n initialize() {\n log(\"Initializing\");\n if (!adContainerEl) {\n const parent = contentVideo.parentElement;\n if (parent) {\n const computed = window.getComputedStyle(parent).position;\n if (computed === \"static\") {\n parent.style.position = \"relative\";\n parentPositionOverridden = true;\n }\n }\n const container = document.createElement(\"div\");\n container.style.position = \"absolute\";\n container.style.left = \"0\";\n container.style.top = \"0\";\n container.style.right = \"0\";\n container.style.bottom = \"0\";\n container.style.display = \"none\";\n container.style.alignItems = \"center\";\n container.style.justifyContent = \"center\";\n container.style.pointerEvents = \"none\";\n container.style.zIndex = AD_LAYER_Z_INDEX;\n container.style.backgroundColor = \"#000\";\n container.style.transition = \"opacity 0.3s ease-in-out\";\n container.style.opacity = \"0\";\n container.style.isolation = \"isolate\";\n const countdown = document.createElement(\"div\");\n countdown.style.position = \"absolute\";\n countdown.style.left = \"12px\";\n countdown.style.top = \"12px\";\n countdown.style.padding = \"4px 8px\";\n countdown.style.borderRadius = \"4px\";\n countdown.style.background = \"rgba(0,0,0,0.75)\";\n countdown.style.color = \"#fff\";\n countdown.style.fontFamily = \"sans-serif\";\n countdown.style.fontSize = \"12px\";\n countdown.style.lineHeight = \"1.2\";\n countdown.style.pointerEvents = \"none\";\n countdown.style.zIndex = COUNTDOWN_Z_INDEX;\n countdown.textContent = \"Ad\";\n container.appendChild(countdown);\n contentVideo.parentElement?.appendChild(container);\n adContainerEl = container;\n adCountdownEl = countdown;\n }\n },\n async requestAds(duration) {\n log(\"Requesting ads for duration:\", duration);\n if (adPlaying) {\n return Promise.reject(new Error(\"Ad already playing\"));\n }\n if (destroyed) {\n return Promise.reject(new Error(\"Player has been destroyed\"));\n }\n try {\n tornDown = false;\n let durationSeconds = 30;\n const parsed = parseInt(duration || \"\", 10);\n if (!isNaN(parsed) && parsed > 0) {\n durationSeconds = parsed;\n }\n const ads = await fetchVast(durationSeconds);\n if (ads.length === 0) {\n log(\"No ads available from VAST response\");\n emit(\"ad_error\");\n return Promise.resolve();\n }\n assignCurrentAd(ads[0]);\n log(`Ad loaded: ${currentAd.title}, duration: ${currentAd.duration}s`);\n return Promise.resolve();\n } catch (error) {\n console.error(\"[AdStormPlayer] Error requesting ads:\", error);\n emit(\"ad_error\");\n return Promise.reject(error);\n }\n },\n async play() {\n if (!currentAd) {\n return Promise.reject(new Error(\"No ad loaded\"));\n }\n if (destroyed) {\n return Promise.reject(new Error(\"Player has been destroyed\"));\n }\n log(\"Starting ad playback\");\n try {\n tornDown = false;\n if (adHideTimerId) {\n clearTimeout(adHideTimerId);\n adHideTimerId = void 0;\n }\n if (!adVideoElement) {\n adVideoElement = createAdVideoElement();\n adContainerEl?.appendChild(adVideoElement);\n } else {\n teardownCurrentPlayback();\n }\n setupAdEventListeners();\n trackingFired = {\n impression: trackingFired.impression,\n start: false,\n firstQuartile: false,\n midpoint: false,\n thirdQuartile: false,\n complete: false\n };\n contentVideo.style.transition = \"opacity 0.3s ease-in-out\";\n contentVideo.style.opacity = \"0\";\n setTimeout(() => {\n contentVideo.style.visibility = \"hidden\";\n }, 300);\n contentVideo.muted = true;\n contentVideo.volume = 0;\n if (!continueLiveStreamDuringAds) {\n contentVideo.pause();\n }\n adPlaying = true;\n setAdPlayingFlag(true);\n if (adVideoElement) {\n adVideoElement.volume = originalMutedState ? 0 : originalVolume;\n adVideoElement.muted = originalMutedState;\n }\n if (adContainerEl) {\n adContainerEl.style.display = \"flex\";\n adContainerEl.style.pointerEvents = \"auto\";\n adContainerEl.offsetHeight;\n adContainerEl.style.opacity = \"1\";\n }\n emit(\"content_pause\");\n const mediaFile = selectBestMediaFile(currentAd.mediaFiles);\n if (!mediaFile) {\n throw new Error(\"No media file available\");\n }\n log(\"Playing media file:\", mediaFile.url);\n adVideoElement.src = mediaFile.url;\n adVideoElement.load();\n await adVideoElement.play();\n return Promise.resolve();\n } catch (error) {\n console.error(\"[AdStormPlayer] Error playing ad:\", error);\n handleAdError();\n return Promise.reject(error);\n }\n },\n async stop() {\n log(\"Stopping ad\");\n tornDown = true;\n adPlaying = false;\n setAdPlayingFlag(false);\n clearAdStallTimer();\n clearAdCountdownTimer();\n if (adContainerEl) {\n adContainerEl.style.opacity = \"0\";\n adHideTimerId = setTimeout(() => {\n if (adContainerEl) {\n adContainerEl.style.display = \"none\";\n adContainerEl.style.pointerEvents = \"none\";\n }\n }, 300);\n }\n teardownCurrentPlayback();\n contentVideo.style.visibility = \"visible\";\n contentVideo.style.opacity = \"1\";\n contentVideo.muted = originalMutedState;\n contentVideo.volume = originalVolume;\n currentAd = void 0;\n return Promise.resolve();\n },\n pause() {\n if (!adPlaying || !adVideoElement) return;\n try {\n if (!adVideoElement.paused) adVideoElement.pause();\n } catch (error) {\n console.warn(\"[AdStormPlayer] Error pausing ad:\", error);\n }\n },\n resume() {\n if (!adPlaying || !adVideoElement) return;\n try {\n if (adVideoElement.paused) adVideoElement.play().catch(() => {\n });\n } catch (error) {\n console.warn(\"[AdStormPlayer] Error resuming ad:\", error);\n }\n },\n destroy() {\n log(\"Destroying\");\n destroyed = true;\n tornDown = true;\n adPlaying = false;\n setAdPlayingFlag(false);\n clearAdStallTimer();\n clearAdCountdownTimer();\n if (adHideTimerId) {\n clearTimeout(adHideTimerId);\n adHideTimerId = void 0;\n }\n contentVideo.muted = originalMutedState;\n contentVideo.volume = originalVolume;\n contentVideo.style.visibility = \"visible\";\n contentVideo.style.opacity = \"1\";\n teardownCurrentPlayback();\n adVideoElement?.remove();\n adVideoElement = void 0;\n if (adContainerEl?.parentElement) {\n adContainerEl.parentElement.removeChild(adContainerEl);\n }\n adContainerEl = void 0;\n adCountdownEl = void 0;\n currentAd = void 0;\n sessionId = void 0;\n preloadSlots.clear();\n listeners.clear();\n if (parentPositionOverridden && contentVideo.parentElement) {\n contentVideo.parentElement.style.position = \"\";\n parentPositionOverridden = false;\n }\n },\n updateOptions(opts) {\n if (opts.continueLiveStreamDuringAds !== void 0) {\n continueLiveStreamDuringAds = opts.continueLiveStreamDuringAds;\n }\n },\n async playAd(requestContext) {\n if (destroyed) return Promise.reject(new Error(\"Player has been destroyed\"));\n if (!currentAd) {\n const ad = await requestAdFromApi(requestContext);\n if (!ad) {\n emit(\"ad_error\", { message: \"No valid ad from AdStorm API\" });\n return Promise.reject(new Error(\"No valid ad from AdStorm API\"));\n }\n assignCurrentAd(ad);\n }\n return this.play();\n },\n async preloadAd(arg1, arg2) {\n if (destroyed) return;\n const token = typeof arg1 === \"string\" ? arg1 : typeof arg2 === \"string\" ? arg2 : void 0;\n if (!token) return;\n if (currentAd) {\n preloadSlots.set(token, { ad: currentAd });\n currentAd = void 0;\n return;\n }\n const requestContext = typeof arg1 === \"string\" ? arg2 : arg1;\n const ad = await requestAdFromApi(requestContext);\n if (!ad) return;\n preloadSlots.set(token, { ad });\n },\n async playPreloaded(token) {\n if (destroyed) return Promise.reject(new Error(\"Player has been destroyed\"));\n const slot = preloadSlots.get(token);\n if (!slot) {\n return Promise.reject(new Error(`No preloaded ad for token ${token}`));\n }\n preloadSlots.delete(token);\n assignCurrentAd(slot.ad);\n return this.play();\n },\n hasPreloaded(token) {\n return preloadSlots.has(token);\n },\n cancelPreload(token) {\n preloadSlots.delete(token);\n },\n isAdPlaying() {\n return adPlaying;\n },\n resize(width, height) {\n log(`Resizing to ${width}x${height}`);\n if (adContainerEl) {\n adContainerEl.style.width = `${width}px`;\n adContainerEl.style.height = `${height}px`;\n }\n if (adVideoElement) {\n adVideoElement.style.width = `${width}px`;\n adVideoElement.style.height = `${height}px`;\n }\n },\n on(event, listener) {\n if (!listeners.has(event)) listeners.set(event, /* @__PURE__ */ new Set());\n listeners.get(event).add(listener);\n },\n off(event, listener) {\n listeners.get(event)?.delete(listener);\n },\n updateOriginalMutedState(muted, volume) {\n const nextVolume = typeof volume === \"number\" && !Number.isNaN(volume) ? Math.max(0, Math.min(1, volume)) : originalVolume;\n log(`updateOriginalMutedState: muted=${muted}, volume=${nextVolume}`);\n originalMutedState = muted;\n originalVolume = nextVolume;\n },\n getOriginalMutedState() {\n return originalMutedState;\n },\n getOriginalVolume() {\n return originalVolume;\n },\n setAdVolume(volume) {\n if (adVideoElement && adPlaying) {\n adVideoElement.volume = Math.max(0, Math.min(1, volume));\n adVideoElement.muted = volume === 0;\n }\n },\n getAdVolume() {\n if (adVideoElement && adPlaying) {\n return adVideoElement.volume;\n }\n return 1;\n },\n showPlaceholder() {\n if (!adContainerEl) {\n const parent = contentVideo.parentElement;\n if (parent) {\n const computed = window.getComputedStyle(parent).position;\n if (computed === \"static\") {\n parent.style.position = \"relative\";\n parentPositionOverridden = true;\n }\n }\n const container = document.createElement(\"div\");\n container.style.position = \"absolute\";\n container.style.left = \"0\";\n container.style.top = \"0\";\n container.style.right = \"0\";\n container.style.bottom = \"0\";\n container.style.display = \"none\";\n container.style.alignItems = \"center\";\n container.style.justifyContent = \"center\";\n container.style.pointerEvents = \"none\";\n container.style.zIndex = AD_LAYER_Z_INDEX;\n container.style.backgroundColor = \"#000\";\n container.style.isolation = \"isolate\";\n const countdown = document.createElement(\"div\");\n countdown.style.position = \"absolute\";\n countdown.style.left = \"12px\";\n countdown.style.top = \"12px\";\n countdown.style.padding = \"4px 8px\";\n countdown.style.borderRadius = \"4px\";\n countdown.style.background = \"rgba(0,0,0,0.75)\";\n countdown.style.color = \"#fff\";\n countdown.style.fontFamily = \"sans-serif\";\n countdown.style.fontSize = \"12px\";\n countdown.style.lineHeight = \"1.2\";\n countdown.style.pointerEvents = \"none\";\n countdown.style.zIndex = COUNTDOWN_Z_INDEX;\n countdown.textContent = \"Ad\";\n container.appendChild(countdown);\n contentVideo.parentElement?.appendChild(container);\n adContainerEl = container;\n adCountdownEl = countdown;\n }\n if (adContainerEl) {\n adContainerEl.style.display = \"flex\";\n adContainerEl.style.opacity = \"1\";\n adContainerEl.style.pointerEvents = \"auto\";\n }\n },\n hidePlaceholder() {\n if (adContainerEl) {\n adContainerEl.style.opacity = \"0\";\n setTimeout(() => {\n if (adContainerEl) {\n adContainerEl.style.display = \"none\";\n adContainerEl.style.pointerEvents = \"none\";\n }\n }, 300);\n }\n }\n };\n}\n\n// src/utils/tracking.ts\nvar cachedBrowserId = null;\nfunction getClientInfo() {\n const ua = navigator.userAgent;\n const platform = navigator.platform;\n const vendor = navigator.vendor || \"\";\n const maxTouchPoints = navigator.maxTouchPoints || 0;\n const memory = navigator.deviceMemory || null;\n const hardwareConcurrency = navigator.hardwareConcurrency || 1;\n const screenInfo = {\n width: screen?.width,\n height: screen?.height,\n availWidth: screen?.availWidth,\n availHeight: screen?.availHeight,\n orientation: screen?.orientation?.type || \"\",\n pixelDepth: screen?.pixelDepth\n };\n let deviceType = \"desktop\";\n let brand = \"Unknown\";\n let os = \"Unknown\";\n let model = \"\";\n let isSmartTV = false;\n let isAndroid = false;\n let isWebView = false;\n let isWebApp = false;\n if (ua.includes(\"Web0S\")) {\n brand = \"LG\";\n os = \"webOS\";\n isSmartTV = true;\n deviceType = \"tv\";\n const webosMatch = ua.match(/Web0S\\/([^\\s]+)/);\n model = webosMatch ? `webOS ${webosMatch[1]}` : \"webOS TV\";\n } else if (ua.includes(\"Tizen\")) {\n brand = \"Samsung\";\n os = \"Tizen\";\n isSmartTV = true;\n deviceType = \"tv\";\n const tizenMatch = ua.match(/Tizen\\/([^\\s]+)/);\n const tvMatch = ua.match(/(?:Smart-TV|SMART-TV|TV)/i) ? \"Smart TV\" : \"\";\n model = tizenMatch ? `Tizen ${tizenMatch[1]} ${tvMatch}`.trim() : \"Tizen TV\";\n } else if (ua.includes(\"Philips\")) {\n brand = \"Philips\";\n os = \"Saphi\";\n isSmartTV = true;\n deviceType = \"tv\";\n } else if (ua.includes(\"Sharp\") || ua.includes(\"AQUOS\")) {\n brand = \"Sharp\";\n os = \"Android TV\";\n isSmartTV = true;\n deviceType = \"tv\";\n } else if (ua.includes(\"Android\") && (ua.includes(\"Sony\") || vendor.includes(\"Sony\"))) {\n brand = \"Sony\";\n os = \"Android TV\";\n isSmartTV = true;\n deviceType = \"tv\";\n } else if (ua.includes(\"Android\") && (ua.includes(\"NetCast\") || ua.includes(\"LG\"))) {\n brand = \"LG\";\n os = \"Android TV\";\n isSmartTV = true;\n deviceType = \"tv\";\n } else if (ua.includes(\" Roku\") || ua.includes(\"Roku/\")) {\n brand = \"Roku\";\n os = \"Roku OS\";\n isSmartTV = true;\n deviceType = \"tv\";\n } else if (ua.includes(\"AppleTV\")) {\n brand = \"Apple\";\n os = \"tvOS\";\n isSmartTV = true;\n deviceType = \"tv\";\n }\n if (ua.includes(\"Android\")) {\n isAndroid = true;\n os = \"Android\";\n deviceType = /Mobile/.test(ua) ? \"mobile\" : \"tablet\";\n if (ua.includes(\"Android\") && (maxTouchPoints === 0 || ua.includes(\"Google TV\") || ua.includes(\"XiaoMi\"))) {\n deviceType = \"tv\";\n isSmartTV = true;\n brand = brand === \"Unknown\" ? \"Android TV\" : brand;\n }\n const androidModelMatch = ua.match(/\\(([^)]*Android[^)]*)\\)/);\n if (androidModelMatch && androidModelMatch[1]) {\n model = androidModelMatch[1];\n }\n }\n if (/iPad|iPhone|iPod/.test(ua)) {\n os = \"iOS\";\n deviceType = \"mobile\";\n brand = \"Apple\";\n if (navigator.maxTouchPoints > 1 && /iPad/.test(ua)) {\n deviceType = \"tablet\";\n }\n }\n if (!isAndroid && !isSmartTV && !/Mobile/.test(ua)) {\n if (ua.includes(\"Windows\")) {\n os = \"Windows\";\n deviceType = \"desktop\";\n } else if (ua.includes(\"Mac\") && !/iPhone/.test(ua)) {\n os = \"macOS\";\n deviceType = \"desktop\";\n if (maxTouchPoints > 1) deviceType = \"tablet\";\n } else if (ua.includes(\"Linux\")) {\n os = \"Linux\";\n deviceType = \"desktop\";\n }\n }\n if (brand === \"Unknown\") {\n if (vendor.includes(\"Google\") || ua.includes(\"Chrome\")) brand = \"Google\";\n if (vendor.includes(\"Apple\")) brand = \"Apple\";\n if (vendor.includes(\"Samsung\") || ua.includes(\"SM-\")) brand = \"Samsung\";\n }\n isWebView = /wv|WebView|Linux; U;/.test(ua);\n if (window?.outerHeight === 0 && window?.outerWidth === 0) {\n isWebView = true;\n }\n isWebApp = window.matchMedia(\"(display-mode: standalone)\").matches || window.navigator.standalone === true || window.screen?.orientation?.angle !== void 0;\n return {\n brand,\n os,\n model: model || ua.substring(0, 50) + \"...\",\n deviceType,\n isSmartTV,\n isAndroid,\n isWebView,\n isWebApp,\n domain: window.location.hostname,\n origin: window.location.origin,\n path: window.location.pathname,\n userAgent: ua,\n vendor,\n platform,\n screen: screenInfo,\n hardwareConcurrency,\n deviceMemory: memory,\n maxTouchPoints,\n language: navigator.language,\n languages: navigator.languages?.join(\",\") || \"\",\n cookieEnabled: navigator.cookieEnabled,\n doNotTrack: navigator.doNotTrack || \"\",\n referrer: document.referrer,\n visibilityState: document.visibilityState\n };\n}\nasync function getBrowserID(clientInfo) {\n if (cachedBrowserId) {\n return cachedBrowserId;\n }\n const fingerprintString = JSON.stringify(clientInfo);\n if (typeof crypto !== \"undefined\" && crypto.subtle && crypto.subtle.digest) {\n try {\n await crypto.subtle.digest(\"SHA-256\", new Uint8Array([1, 2, 3]));\n let encodedData;\n if (typeof TextEncoder !== \"undefined\") {\n encodedData = new TextEncoder().encode(fingerprintString);\n } else {\n const utf8 = unescape(encodeURIComponent(fingerprintString));\n const buffer = new Uint8Array(utf8.length);\n for (let i = 0; i < utf8.length; i++) {\n buffer[i] = utf8.charCodeAt(i);\n }\n encodedData = buffer;\n }\n const hashBuffer = await crypto.subtle.digest(\"SHA-256\", encodedData);\n const hashArray = Array.from(new Uint8Array(hashBuffer));\n const hashHex = hashArray.map((b) => b.toString(16).padStart(2, \"0\")).join(\"\");\n cachedBrowserId = hashHex;\n return hashHex;\n } catch (error) {\n console.warn(\n \"[StormcloudVideoPlayer] crypto.subtle.digest not supported, using fallback hash\"\n );\n }\n }\n let hash = 0;\n for (let i = 0; i < fingerprintString.length; i++) {\n const char = fingerprintString.charCodeAt(i);\n hash = (hash << 5) - hash + char;\n hash = hash & hash;\n }\n const fallbackHash = Math.abs(hash).toString(16).padStart(8, \"0\");\n const timestamp = Date.now().toString(16).padStart(12, \"0\");\n const random = Math.random().toString(16).substring(2, 14).padStart(12, \"0\");\n cachedBrowserId = (fallbackHash + timestamp + random).padEnd(64, \"0\");\n return cachedBrowserId;\n}\nvar TRACK_URL = \"https://adstorm.co/api-adstorm-dev/adstorm/player-tracking/track\";\nasync function sendTrackRequest(licenseKey, body) {\n const headers = {\n \"Content-Type\": \"application/json\"\n };\n if (licenseKey) {\n headers[\"Authorization\"] = `Bearer ${licenseKey}`;\n }\n const response = await fetch(TRACK_URL, {\n method: \"POST\",\n headers,\n body: JSON.stringify(body)\n });\n if (!response.ok) {\n throw new Error(`HTTP error! status: ${response.status}`);\n }\n await response.json();\n}\nasync function sendInitialTracking(licenseKey) {\n try {\n const clientInfo = getClientInfo();\n const browserId = await getBrowserID(clientInfo);\n const trackingData = {\n browserId,\n ...clientInfo\n };\n const headers = {\n \"Content-Type\": \"application/json\"\n };\n if (licenseKey) {\n headers[\"Authorization\"] = `Bearer ${licenseKey}`;\n }\n const response = await fetch(TRACK_URL, {\n method: \"POST\",\n headers,\n body: JSON.stringify(trackingData)\n });\n if (!response.ok) {\n throw new Error(`HTTP error! status: ${response.status}`);\n }\n await response.json();\n } catch (error) {\n console.error(\n \"[StormcloudVideoPlayer] Error sending initial tracking data:\",\n error\n );\n }\n}\nasync function sendAdLoadedTracking(licenseKey, adLoadedInfo) {\n try {\n const clientInfo = getClientInfo();\n const browserId = await getBrowserID(clientInfo);\n const trackingData = { browserId, ...clientInfo };\n await sendTrackRequest(licenseKey, {\n ...trackingData,\n licenseKey,\n adLoadedInfo\n });\n } catch (error) {\n console.error(\n \"[StormcloudVideoPlayer] Error sending ad loaded tracking:\",\n error\n );\n }\n}\nasync function sendAdImpressionTracking(licenseKey, adImpressionInfo) {\n try {\n const clientInfo = getClientInfo();\n const browserId = await getBrowserID(clientInfo);\n const trackingData = { browserId, ...clientInfo };\n await sendTrackRequest(licenseKey, {\n ...trackingData,\n licenseKey,\n adImpressionInfo\n });\n } catch (error) {\n console.error(\n \"[StormcloudVideoPlayer] Error sending ad impression tracking:\",\n error\n );\n }\n}\nasync function sendHeartbeat(licenseKey) {\n try {\n const clientInfo = getClientInfo();\n const browserId = await getBrowserID(clientInfo);\n const heartbeatData = {\n browserId,\n timestamp: (/* @__PURE__ */ new Date()).toISOString()\n };\n const headers = {\n \"Content-Type\": \"application/json\"\n };\n if (licenseKey) {\n headers[\"Authorization\"] = `Bearer ${licenseKey}`;\n }\n const response = await fetch(\n \"https://adstorm.co/api-adstorm-dev/adstorm/player-tracking/heartbeat\",\n {\n method: \"POST\",\n headers,\n body: JSON.stringify(heartbeatData)\n }\n );\n if (!response.ok) {\n throw new Error(`HTTP error! status: ${response.status}`);\n }\n await response.json();\n } catch (error) {\n console.error(\"[StormcloudVideoPlayer] Error sending heartbeat:\", error);\n }\n}\n\n// src/utils/polyfills.ts\nfunction polyfillURLSearchParams() {\n if (typeof URLSearchParams !== \"undefined\") {\n return;\n }\n class URLSearchParamsPolyfill {\n constructor(init) {\n this.params = /* @__PURE__ */ new Map();\n if (typeof init === \"string\") {\n this.parseQueryString(init);\n } else if (init instanceof URLSearchParamsPolyfill) {\n init.forEach((value, key) => {\n this.append(key, value);\n });\n }\n }\n parseQueryString(query) {\n const cleanQuery = query.startsWith(\"?\") ? query.slice(1) : query;\n if (!cleanQuery) return;\n cleanQuery.split(\"&\").forEach((param) => {\n const [key, value] = param.split(\"=\");\n if (key) {\n const decodedKey = this.safeDecodeURIComponent(key);\n const decodedValue = value ? this.safeDecodeURIComponent(value) : \"\";\n this.append(decodedKey, decodedValue);\n }\n });\n }\n safeDecodeURIComponent(str) {\n try {\n return decodeURIComponent(str.replace(/\\+/g, \" \"));\n } catch (e) {\n return str;\n }\n }\n append(name, value) {\n const values = this.params.get(name) || [];\n values.push(String(value));\n this.params.set(name, values);\n }\n delete(name) {\n this.params.delete(name);\n }\n get(name) {\n const values = this.params.get(name);\n return values && values.length > 0 && values[0] !== void 0 ? values[0] : null;\n }\n getAll(name) {\n return this.params.get(name) || [];\n }\n has(name) {\n return this.params.has(name);\n }\n set(name, value) {\n this.params.set(name, [String(value)]);\n }\n forEach(callback) {\n this.params.forEach((values, key) => {\n values.forEach((value) => {\n callback(value, key, this);\n });\n });\n }\n toString() {\n const parts = [];\n this.params.forEach((values, key) => {\n values.forEach((value) => {\n parts.push(`${encodeURIComponent(key)}=${encodeURIComponent(value)}`);\n });\n });\n return parts.join(\"&\");\n }\n }\n window.URLSearchParams = URLSearchParamsPolyfill;\n}\nfunction polyfillTextEncoder() {\n if (typeof TextEncoder !== \"undefined\") {\n return;\n }\n class TextEncoderPolyfill {\n constructor() {\n this.encoding = \"utf-8\";\n }\n encode(str) {\n const utf8 = [];\n for (let i = 0; i < str.length; i++) {\n let charcode = str.charCodeAt(i);\n if (charcode < 128) {\n utf8.push(charcode);\n } else if (charcode < 2048) {\n utf8.push(192 | charcode >> 6, 128 | charcode & 63);\n } else if (charcode < 55296 || charcode >= 57344) {\n utf8.push(\n 224 | charcode >> 12,\n 128 | charcode >> 6 & 63,\n 128 | charcode & 63\n );\n } else {\n i++;\n charcode = 65536 + ((charcode & 1023) << 10 | str.charCodeAt(i) & 1023);\n utf8.push(\n 240 | charcode >> 18,\n 128 | charcode >> 12 & 63,\n 128 | charcode >> 6 & 63,\n 128 | charcode & 63\n );\n }\n }\n return new Uint8Array(utf8);\n }\n }\n window.TextEncoder = TextEncoderPolyfill;\n}\nfunction polyfillPromiseFinally() {\n if (typeof Promise !== \"undefined\" && !Promise.prototype.finally) {\n Promise.prototype.finally = function(callback) {\n const constructor = this.constructor;\n return this.then(\n (value) => constructor.resolve(callback()).then(() => value),\n (reason) => constructor.resolve(callback()).then(() => {\n throw reason;\n })\n );\n };\n }\n}\nfunction polyfillObjectAssign() {\n if (typeof Object.assign !== \"function\") {\n Object.assign = function(target, ...sources) {\n if (target == null) {\n throw new TypeError(\"Cannot convert undefined or null to object\");\n }\n const to = Object(target);\n for (let i = 0; i < sources.length; i++) {\n const nextSource = sources[i];\n if (nextSource != null) {\n for (const nextKey in nextSource) {\n if (Object.prototype.hasOwnProperty.call(nextSource, nextKey)) {\n to[nextKey] = nextSource[nextKey];\n }\n }\n }\n }\n return to;\n };\n }\n}\nfunction polyfillArrayFrom() {\n if (!Array.from) {\n Array.from = function(arrayLike, mapFn, thisArg) {\n const items = Object(arrayLike);\n if (arrayLike == null) {\n throw new TypeError(\"Array.from requires an array-like object\");\n }\n const len = items.length >>> 0;\n const result = new Array(len);\n for (let i = 0; i < len; i++) {\n if (mapFn) {\n result[i] = mapFn.call(thisArg, items[i], i);\n } else {\n result[i] = items[i];\n }\n }\n return result;\n };\n }\n}\nfunction polyfillStringStartsWith() {\n if (!String.prototype.startsWith) {\n String.prototype.startsWith = function(search, pos) {\n pos = !pos || pos < 0 ? 0 : +pos;\n return this.substring(pos, pos + search.length) === search;\n };\n }\n}\nfunction polyfillStringEndsWith() {\n if (!String.prototype.endsWith) {\n String.prototype.endsWith = function(search, length) {\n if (length === void 0 || length > this.length) {\n length = this.length;\n }\n return this.substring(length - search.length, length) === search;\n };\n }\n}\nfunction polyfillStringIncludes() {\n if (!String.prototype.includes) {\n String.prototype.includes = function(search, start) {\n if (typeof start !== \"number\") {\n start = 0;\n }\n if (start + search.length > this.length) {\n return false;\n }\n return this.indexOf(search, start) !== -1;\n };\n }\n}\nfunction initializePolyfills() {\n polyfillObjectAssign();\n polyfillArrayFrom();\n polyfillStringStartsWith();\n polyfillStringEndsWith();\n polyfillStringIncludes();\n polyfillURLSearchParams();\n polyfillTextEncoder();\n polyfillPromiseFinally();\n}\n\n// src/utils/browserCompat.ts\nfunction getChromeVersion(ua) {\n const match = ua.match(/Chrome\\/(\\d+)/);\n return match && match[1] ? parseInt(match[1], 10) : 0;\n}\nfunction getWebKitVersion(ua) {\n const match = ua.match(/AppleWebKit\\/(\\d+)/);\n return match && match[1] ? parseInt(match[1], 10) : 0;\n}\nfunction getPlatform() {\n if (\"userAgentData\" in navigator && navigator.userAgentData?.platform) {\n return navigator.userAgentData.platform;\n }\n const ua = navigator.userAgent;\n if (/Mac|iPhone|iPad|iPod/i.test(ua)) {\n return /iPhone|iPad|iPod/i.test(ua) ? \"iPhone\" : \"MacIntel\";\n }\n if (/Win/i.test(ua)) {\n return \"Win32\";\n }\n if (/Linux/i.test(ua)) {\n return /Android/i.test(ua) ? \"Linux armv8l\" : \"Linux x86_64\";\n }\n if (/CrOS/i.test(ua)) {\n return \"CrOS\";\n }\n return navigator.platform || \"Unknown\";\n}\nfunction detectBrowser() {\n const ua = navigator.userAgent;\n const platform = getPlatform();\n let name = \"Unknown\";\n let version = \"0\";\n let majorVersion = 0;\n let isSmartTV = false;\n let isLegacyTV = false;\n let supportsIMA = true;\n let supportsModernJS = true;\n let recommendedAdPlayer = \"ima\";\n let webOSVersion;\n let tizenVersion;\n let chromeVersionNum;\n const chromeVersion = getChromeVersion(ua);\n const webkitVersion = getWebKitVersion(ua);\n chromeVersionNum = chromeVersion > 0 ? chromeVersion : void 0;\n if (/Web0S|webOS|LG Browser|LGSTB/i.test(ua)) {\n name = \"LG WebOS\";\n isSmartTV = true;\n let match = ua.match(/Web0S[/\\s]*([\\d.]+)/i) || ua.match(/webOS[/\\s]*([\\d.]+)/i);\n if (!match || !match[1]) {\n match = ua.match(/webOSTV[/\\s-]*([\\d.]+)/i) || ua.match(/webOS\\.TV[/\\s-]*([\\d.]+)/i);\n }\n if (match && match[1]) {\n version = match[1];\n const parts = version.split(\".\");\n majorVersion = parts[0] ? parseInt(parts[0], 10) : 0;\n webOSVersion = majorVersion;\n } else if (chromeVersion > 0) {\n if (chromeVersion >= 79) {\n webOSVersion = 6;\n version = \"6.0\";\n majorVersion = 6;\n } else if (chromeVersion >= 68) {\n webOSVersion = 5;\n version = \"5.0\";\n majorVersion = 5;\n } else if (chromeVersion >= 53) {\n webOSVersion = 4;\n version = \"4.0\";\n majorVersion = 4;\n } else if (chromeVersion >= 38) {\n webOSVersion = 3;\n version = \"3.0\";\n majorVersion = 3;\n } else {\n webOSVersion = 2;\n version = \"2.0\";\n majorVersion = 2;\n }\n } else {\n version = \"Unknown\";\n webOSVersion = void 0;\n }\n if (webOSVersion !== void 0 && webOSVersion >= 4) {\n supportsIMA = true;\n recommendedAdPlayer = \"ima\";\n isLegacyTV = false;\n } else if (webOSVersion !== void 0 && webOSVersion >= 3) {\n if (chromeVersion >= 53) {\n supportsIMA = true;\n recommendedAdPlayer = \"ima\";\n isLegacyTV = false;\n } else {\n supportsIMA = false;\n recommendedAdPlayer = \"hls\";\n isLegacyTV = true;\n }\n } else if (chromeVersion >= 53) {\n supportsIMA = true;\n recommendedAdPlayer = \"ima\";\n isLegacyTV = false;\n } else {\n supportsIMA = false;\n recommendedAdPlayer = \"hls\";\n isLegacyTV = true;\n }\n } else if (/Tizen/i.test(ua)) {\n name = \"Samsung Tizen\";\n isSmartTV = true;\n const match = ua.match(/Tizen[/\\s]*([\\d.]+)/i);\n version = match && match[1] ? match[1] : \"Unknown\";\n if (version !== \"Unknown\") {\n const parts = version.split(\".\");\n majorVersion = parts[0] ? parseInt(parts[0], 10) : 0;\n tizenVersion = majorVersion;\n }\n if (tizenVersion !== void 0 && tizenVersion >= 4) {\n supportsIMA = true;\n recommendedAdPlayer = \"ima\";\n isLegacyTV = false;\n } else if (tizenVersion !== void 0 && tizenVersion >= 3 && chromeVersion >= 47) {\n supportsIMA = true;\n recommendedAdPlayer = \"ima\";\n isLegacyTV = false;\n } else if (chromeVersion >= 53) {\n supportsIMA = true;\n recommendedAdPlayer = \"ima\";\n isLegacyTV = false;\n } else {\n supportsIMA = false;\n recommendedAdPlayer = \"hls\";\n isLegacyTV = true;\n }\n } else if (/SMART-TV|SmartTV/i.test(ua)) {\n name = \"Smart TV\";\n isSmartTV = true;\n if (chromeVersion >= 53) {\n supportsIMA = true;\n recommendedAdPlayer = \"ima\";\n } else {\n supportsIMA = false;\n recommendedAdPlayer = \"hls\";\n isLegacyTV = true;\n }\n } else if (/NetCast/i.test(ua)) {\n name = \"LG NetCast\";\n isSmartTV = true;\n isLegacyTV = true;\n supportsIMA = false;\n recommendedAdPlayer = \"hls\";\n } else if (/BRAVIA/i.test(ua)) {\n name = \"Sony BRAVIA\";\n isSmartTV = true;\n if (chromeVersion >= 53) {\n supportsIMA = true;\n recommendedAdPlayer = \"ima\";\n } else {\n supportsIMA = false;\n recommendedAdPlayer = \"hls\";\n isLegacyTV = true;\n }\n } else {\n if (chromeVersion > 0) {\n name = \"Chrome\";\n version = chromeVersion.toString();\n majorVersion = chromeVersion;\n if (chromeVersion < 50) {\n supportsIMA = false;\n supportsModernJS = false;\n recommendedAdPlayer = \"hls\";\n }\n }\n if (webkitVersion > 0 && webkitVersion < 600) {\n supportsModernJS = false;\n if (chromeVersion < 50) {\n supportsIMA = false;\n recommendedAdPlayer = \"hls\";\n }\n }\n }\n if (typeof Promise === \"undefined\" || typeof Map === \"undefined\" || typeof Set === \"undefined\") {\n supportsModernJS = false;\n supportsIMA = false;\n recommendedAdPlayer = \"hls\";\n }\n if (typeof URLSearchParams === \"undefined\") {\n supportsModernJS = false;\n }\n return {\n name,\n version,\n majorVersion,\n isSmartTV,\n isLegacyTV,\n platform,\n supportsIMA,\n supportsModernJS,\n recommendedAdPlayer,\n webOSVersion,\n tizenVersion,\n chromeVersion: chromeVersionNum\n };\n}\nfunction supportsGoogleIMA() {\n const browser = detectBrowser();\n if (browser.isLegacyTV) {\n return false;\n }\n if (typeof document === \"undefined\" || typeof document.createElement !== \"function\") {\n return false;\n }\n try {\n const video = document.createElement(\"video\");\n if (!video) {\n return false;\n }\n } catch (e) {\n return false;\n }\n if (typeof Promise === \"undefined\") {\n return false;\n }\n return browser.supportsIMA;\n}\nfunction logBrowserInfo(debug = false) {\n if (!debug) return;\n const browser = detectBrowser();\n const imaSupport = supportsGoogleIMA();\n console.log(\"[StormcloudVideoPlayer] Browser Compatibility Info:\", {\n browser: `${browser.name} ${browser.version}`,\n platform: browser.platform,\n isSmartTV: browser.isSmartTV,\n isLegacyTV: browser.isLegacyTV,\n supportsIMA: imaSupport,\n supportsModernJS: browser.supportsModernJS,\n recommendedAdPlayer: browser.recommendedAdPlayer,\n ...browser.webOSVersion !== void 0 ? { webOSVersion: browser.webOSVersion } : {},\n ...browser.tizenVersion !== void 0 ? { tizenVersion: browser.tizenVersion } : {},\n ...browser.chromeVersion !== void 0 ? { chromeVersion: browser.chromeVersion } : {},\n userAgent: navigator.userAgent\n });\n}\nfunction getBrowserConfigOverrides() {\n const browser = detectBrowser();\n const overrides = {};\n if (browser.isSmartTV) {\n overrides.allowNativeHls = true;\n }\n return overrides;\n}\n\n// src/player/StormcloudVideoPlayer.ts\nvar DEBUG_HISTORY_LIMIT = 120;\nvar StormcloudVideoPlayer = class {\n constructor(config) {\n this.pendingNextAdBids = null;\n this.continuousFetchLoopPromise = null;\n this.attached = false;\n this.inAdBreak = false;\n this.adPodQueue = [];\n this.lastHeartbeatTime = 0;\n this.currentAdIndex = 0;\n this.totalAdsInBreak = 0;\n this.showAds = false;\n this.isLiveStream = false;\n this.nativeHlsMode = false;\n this.videoSrcProtection = null;\n this.bufferedSegmentsCount = 0;\n this.shouldAutoplayAfterBuffering = false;\n this.hasInitialBufferCompleted = false;\n this.activeAdRequestToken = null;\n this.adRequestWatchdogToken = null;\n this.adFailsafeToken = null;\n this.continuousFetchingActive = false;\n this.isInAdTransition = false;\n this.maxPlaceholderDurationMs = 5e3;\n this.isShowingPlaceholder = false;\n this.lastAdInsertionPoint = null;\n this.processedAdInsertionUpdatedAt = null;\n this.totalAdRequestsInBreak = 0;\n this.maxTotalAdRequestsPerBreak = 20;\n this.pendingAdBreak = null;\n this.savedMutedStateBeforeAd = null;\n this.adLayerInitialized = false;\n this.consecutiveFailures = 0;\n this.maxConsecutiveFailures = 5;\n this.lastAdRequestTime = 0;\n this.minAdRequestIntervalMs = 2500;\n this.backoffBaseMs = 1e3;\n this.maxBackoffMs = 15e3;\n this.MIN_AD_REMAINING_MS = 15e3;\n this.adRequestTimeoutMs = 5e3;\n this.adRequestMaxRetries = 3;\n this.adRequestRetryBackoffMs = 1500;\n this.preloadedTokens = [];\n this.debugLogEntries = [];\n this.adInsertionDebugHistory = [];\n initializePolyfills();\n const browserOverrides = getBrowserConfigOverrides();\n this.config = { ...browserOverrides, ...config };\n this.video = config.videoElement;\n this.adTransitionGapMs = this.config.adTransitionGapMs ?? 100;\n logBrowserInfo(config.debugAdTiming);\n const browserForAdLayer = detectBrowser();\n const isSinglePipeline = browserForAdLayer.isSmartTV || !!this.config.singlePipelineMode;\n this.adLayer = createAdStormPlayer(this.video, {\n licenseKey: this.config.licenseKey || \"\",\n debug: !!config.debugAdTiming,\n ...this.config.channelId != null && { channelId: this.config.channelId }\n });\n this.adLayer.updateOptions({\n continueLiveStreamDuringAds: !isSinglePipeline && this.shouldContinueLiveStreamDuringAds()\n });\n }\n async adRequest(context) {\n if (this.config.disableAds) return [];\n const durationSeconds = Math.max(\n 1,\n Math.ceil(context?.remainingBreakSec ?? context?.breakDurationSec ?? 30)\n );\n await this.adLayer.requestAds(String(durationSeconds));\n return [\n {\n bidder: \"adstorm-direct\",\n cpm: 0,\n width: 0,\n height: 0,\n adId: \"adstorm\",\n impId: \"\",\n creativeId: \"adstorm\",\n currency: \"USD\",\n durationSec: durationSeconds\n }\n ];\n }\n async load() {\n if (!this.attached) {\n this.attach();\n }\n this.initializeTracking();\n if (this.shouldUseNativeHls()) {\n this.nativeHlsMode = true;\n this.videoSrcProtection = this.config.src;\n this.video.src = this.config.src;\n this.isLiveStream = this.config.lowLatencyMode ?? false;\n if (this.config.debugAdTiming) {\n console.log(\n \"[StormcloudVideoPlayer] Using native HLS playback - VOD mode:\",\n {\n isLive: this.isLiveStream,\n allowNativeHls: this.config.allowNativeHls,\n adBehavior: \"vod (main video pauses during ads)\"\n }\n );\n }\n if (!this.config.disableAds) {\n this.adLayer.updateOptions({ continueLiveStreamDuringAds: false, mainHlsInstance: null });\n }\n if (this.config.autoplay) {\n await this.video.play()?.catch(() => {\n });\n }\n return;\n }\n this.hls = new import_hls.default({\n enableWorker: true,\n backBufferLength: 30,\n liveDurationInfinity: true,\n lowLatencyMode: !!this.config.lowLatencyMode,\n maxLiveSyncPlaybackRate: this.config.lowLatencyMode ? 1.5 : 1,\n ...this.config.lowLatencyMode ? { liveSyncDuration: 2 } : {},\n maxBufferLength: 30,\n maxMaxBufferLength: 600,\n maxBufferSize: 60 * 1e3 * 1e3,\n maxBufferHole: 0.5,\n highBufferWatchdogPeriod: 2,\n nudgeOffset: 0.1,\n nudgeMaxRetry: 3,\n startPosition: -1\n });\n this.hls.on(import_hls.default.Events.MEDIA_ATTACHED, () => {\n this.hls?.loadSource(this.config.src);\n });\n this.hls.on(import_hls.default.Events.MANIFEST_PARSED, async (_, data) => {\n if (this.config.allowNativeHls === false) {\n this.isLiveStream = true;\n } else {\n this.isLiveStream = this.hls?.levels?.some(\n (level) => level?.details?.live === true || level?.details?.type === \"LIVE\"\n ) ?? false;\n }\n if (this.config.debugAdTiming) {\n const adBehavior = this.shouldContinueLiveStreamDuringAds() ? \"live (main video continues muted during ads)\" : \"vod (main video pauses during ads)\";\n console.log(\"[StormcloudVideoPlayer] Stream type detected:\", {\n isLive: this.isLiveStream,\n allowNativeHls: this.config.allowNativeHls,\n adBehavior\n });\n }\n if (!this.config.disableAds) {\n this.adLayer.updateOptions({\n continueLiveStreamDuringAds: this.shouldContinueLiveStreamDuringAds(),\n mainHlsInstance: this.hls ?? null\n });\n }\n this.bufferedSegmentsCount = 0;\n this.hasInitialBufferCompleted = false;\n this.shouldAutoplayAfterBuffering = !!this.config.autoplay;\n const minSegments = this.config.minSegmentsBeforePlay ?? 2;\n if (this.config.debugAdTiming) {\n console.log(\n \"[StormcloudVideoPlayer] Waiting for\",\n minSegments,\n \"segments to buffer before playback\"\n );\n }\n if (minSegments === 0 || !this.config.autoplay) {\n this.hasInitialBufferCompleted = true;\n if (this.config.autoplay) {\n await this.video.play()?.catch(() => {\n });\n }\n }\n if (!this.config.disableAds && this.config.projectId) {\n this.startAdInsertionPolling();\n }\n });\n this.hls.on(import_hls.default.Events.LEVEL_LOADED, () => {\n if (this.inAdBreak || this.pendingAdBreak) {\n return;\n }\n this.checkAdInsertionInManifest();\n });\n this.hls.on(import_hls.default.Events.FRAG_BUFFERED, async (_evt, data) => {\n if (this.hasInitialBufferCompleted) {\n return;\n }\n this.bufferedSegmentsCount++;\n const minSegments = this.config.minSegmentsBeforePlay ?? 2;\n if (this.config.debugAdTiming) {\n console.log(\n `[StormcloudVideoPlayer] Buffered segment ${this.bufferedSegmentsCount}/${minSegments}`\n );\n }\n if (this.bufferedSegmentsCount >= minSegments) {\n this.hasInitialBufferCompleted = true;\n if (this.shouldAutoplayAfterBuffering) {\n if (this.inAdBreak || this.adLayer.isAdPlaying()) {\n if (this.config.debugAdTiming) {\n console.log(\n `[StormcloudVideoPlayer] Initial buffer complete (${this.bufferedSegmentsCount} segments). Ad break active \\u2014 deferring play() to handleAdPodComplete().`\n );\n }\n } else {\n if (this.config.debugAdTiming) {\n console.log(\n `[StormcloudVideoPlayer] Initial buffer complete (${this.bufferedSegmentsCount} segments). Starting playback.`\n );\n }\n await this.video.play()?.catch((err) => {\n if (this.config.debugAdTiming) {\n console.warn(\"[StormcloudVideoPlayer] Autoplay failed:\", err);\n }\n });\n }\n }\n }\n });\n this.hls.on(import_hls.default.Events.FRAG_CHANGED, (_evt, data) => {\n const frag = data?.frag;\n if (!frag) return;\n if (this.lastAdInsertionPoint && !this.inAdBreak && this.lastAdInsertionPoint.updated_at !== this.processedAdInsertionUpdatedAt) {\n const segmentName = this.lastAdInsertionPoint.segment_ts_name;\n if (this.fragmentMatchesSegment(frag, segmentName)) {\n this.processedAdInsertionUpdatedAt = this.lastAdInsertionPoint.updated_at;\n const offsetMs = (this.lastAdInsertionPoint.offset_seconds || 0) * 1e3;\n const durationSeconds = this.pendingAdBreak?.durationSeconds ?? 60;\n const withPrefetch = this.pendingAdBreak != null;\n this.pushAdInsertionDebug(\"segment_playing\", segmentName, {\n offsetSeconds: this.lastAdInsertionPoint.offset_seconds,\n detail: `sn=${frag?.sn ?? \"?\"}${withPrefetch ? \" (prefetch active)\" : \"\"}`\n });\n if (this.config.debugAdTiming) {\n console.log(\n `[StormcloudVideoPlayer] Ad insertion segment \"${segmentName}\" now playing \\u2014 scheduling ad start in ${offsetMs}ms` + (withPrefetch ? \" (prefetch was active, preloaded tokens will be used)\" : \"\")\n );\n }\n this.pushAdInsertionDebug(\"ad_scheduled\", segmentName, {\n offsetSeconds: this.lastAdInsertionPoint.offset_seconds,\n detail: `in ${offsetMs}ms, dur=${durationSeconds}s${withPrefetch ? \" (with prefetch)\" : \"\"}`\n });\n this.clearAdInsertionOffsetTimer();\n this.adInsertionOffsetTimerId = window.setTimeout(() => {\n this.adInsertionOffsetTimerId = void 0;\n if (this.inAdBreak) return;\n this.pushAdInsertionDebug(\"ad_triggered\", segmentName, {\n detail: `ad break started (${durationSeconds}s${withPrefetch ? \", with prefetch\" : \"\"})`\n });\n void this.handleAdStart(durationSeconds);\n }, offsetMs);\n }\n }\n });\n this.hls.on(import_hls.default.Events.FRAG_PARSING_USERDATA, (_evt, data) => {\n const samples = data?.samples ?? [];\n for (const sample of samples) {\n const bytes = sample?.data;\n if (!bytes || bytes.length < 5) continue;\n const isSCTE35 = bytes[0] === 252;\n if (!isSCTE35) continue;\n const segName = data?.frag?.relurl ?? data?.frag?.url ?? \"\";\n this.pushAdInsertionDebug(\"scte35_inserted\", segName, {\n detail: `len=${bytes.length}B`\n });\n }\n });\n this.hls.on(import_hls.default.Events.ERROR, (_evt, data) => {\n if (data?.fatal) {\n switch (data.type) {\n case import_hls.default.ErrorTypes.NETWORK_ERROR:\n this.hls?.startLoad();\n break;\n case import_hls.default.ErrorTypes.MEDIA_ERROR:\n this.hls?.recoverMediaError();\n break;\n default:\n this.destroy();\n break;\n }\n }\n });\n this.hls.attachMedia(this.video);\n }\n getAdSource() {\n return \"vast\";\n }\n attachAdLayerEventListeners() {\n this.adLayer.on(\"ad_impression\", () => {\n if (this.config.licenseKey) {\n sendAdImpressionTracking(this.config.licenseKey, {\n source: this.getAdSource(),\n adIndex: this.currentAdIndex,\n timestamp: (/* @__PURE__ */ new Date()).toISOString()\n });\n }\n });\n this.adLayer.on(\"ad_error\", (errorPayload) => {\n let errorMessage = \"Ad playback failed\";\n if (errorPayload) {\n const errorCode = errorPayload.code || errorPayload.errorCode || \"unknown\";\n const vastErrorCode = errorPayload.vastErrorCode;\n const message = errorPayload.message || errorPayload.errorMessage || \"Unknown error\";\n const cause = errorPayload.cause || errorPayload.innerError || errorPayload.error;\n errorMessage = `Ad error: AdError ${errorCode}: ${message}`;\n if (vastErrorCode && vastErrorCode !== \"N/A\" && vastErrorCode !== errorCode) {\n errorMessage += ` (VAST Error Code: ${vastErrorCode})`;\n }\n if (cause) {\n const causeMessage = typeof cause === \"string\" ? cause : cause.message || String(cause);\n errorMessage += `. Caused by: ${causeMessage}`;\n }\n }\n this.pushDebugLog(\"error\", \"ad\", errorMessage, {\n ...errorPayload ? { payload: errorPayload } : {}\n });\n console.error(\"[AD-ERROR]\", errorMessage, errorPayload || \"\");\n this.adLayer.stop().catch(() => {\n });\n this.handleAdFailure();\n });\n this.adLayer.on(\"content_pause\", () => {\n this.clearAdFailsafeTimer();\n this.clearAdRequestWatchdog();\n this.activeAdRequestToken = null;\n this.showAds = true;\n if (this.config.disableFiller) {\n if (this.savedMutedStateBeforeAd == null) {\n this.savedMutedStateBeforeAd = { muted: this.video.muted, volume: this.video.volume };\n this.adLayer.updateOriginalMutedState(this.video.muted, this.video.volume);\n }\n if (!this.video.muted) {\n this.video.muted = true;\n this.video.volume = 0;\n }\n this.adLayer.showPlaceholder();\n }\n if (this.inAdBreak && this.expectedAdBreakDurationMs != null && this.adStopTimerId == null) {\n this.scheduleAdStopCountdown(this.getRemainingAdMs());\n if (this.config.debugAdTiming) {\n console.log(\"[StormcloudVideoPlayer] Starting ad break timer on content_pause (first ad starting)\");\n }\n }\n this.adLayer.setAdVolume(\n this.adLayer.getOriginalMutedState() ? 1 : this.adLayer.getOriginalVolume()\n );\n this.stopFillerBreakTimer();\n this.hidePlaceholderLayer();\n this.isShowingPlaceholder = false;\n if (this.config.debugAdTiming) {\n console.log(\"[StormcloudVideoPlayer] Hiding placeholder - new ads starting\");\n }\n });\n this.adLayer.on(\"content_resume\", () => {\n const remaining = this.getRemainingAdMs();\n const breakMuted = this.savedMutedStateBeforeAd?.muted ?? this.adLayer.getOriginalMutedState();\n const breakVolume = this.savedMutedStateBeforeAd?.volume ?? this.adLayer.getOriginalVolume();\n if (this.config.debugAdTiming) {\n console.log(\n \"[StormcloudVideoPlayer] content_resume received, inAdBreak=%s, remaining=%s, preloadedTokens=%d, pendingNext=%s\",\n this.inAdBreak,\n remaining,\n this.preloadedTokens.length,\n !!this.pendingNextAdBids\n );\n }\n this.clearAdFailsafeTimer();\n this.clearAdRequestWatchdog();\n this.activeAdRequestToken = null;\n this.showAds = false;\n if (!this.inAdBreak) {\n this.video.style.visibility = \"visible\";\n this.video.style.opacity = \"1\";\n this.syncMainContentAudioWhenVisible();\n return;\n }\n this.consecutiveFailures = 0;\n if (!this.config.disableFiller && !this.video.muted) {\n this.video.muted = true;\n this.video.volume = 0;\n }\n if (this.preloadedTokens.length > 0) {\n const token = this.preloadedTokens.shift();\n const remainingNow = this.getRemainingAdMs();\n if (this.expectedAdBreakDurationMs != null && remainingNow < this.MIN_AD_REMAINING_MS) {\n if (this.config.debugAdTiming) {\n console.log(\"[StormcloudVideoPlayer] content_resume: skip preloaded ad, only\", remainingNow, \"ms left\");\n }\n this.adLayer.cancelPreload(token);\n } else {\n this.video.style.transition = \"none\";\n this.video.style.opacity = \"0\";\n this.video.style.visibility = \"hidden\";\n if (!this.config.singlePipelineMode) {\n this.showPlaceholderLayer();\n }\n this.adLayer.showPlaceholder();\n this.isInAdTransition = true;\n setTimeout(() => {\n this.isInAdTransition = false;\n if (!this.inAdBreak) return;\n this.currentAdIndex++;\n this.adLayer.playPreloaded(token).catch((err) => {\n if (this.config.debugAdTiming) console.warn(\"[StormcloudVideoPlayer] playPreloaded failed:\", err);\n this.handleAdFailure();\n });\n }, this.adTransitionGapMs);\n return;\n }\n }\n if (this.pendingNextAdBids && this.pendingNextAdBids.length > 0) {\n const bids = [...this.pendingNextAdBids];\n this.pendingNextAdBids = null;\n const remainingNow = this.getRemainingAdMs();\n if (this.expectedAdBreakDurationMs != null && remainingNow < this.MIN_AD_REMAINING_MS) {\n if (this.config.debugAdTiming) {\n console.log(\"[StormcloudVideoPlayer] content_resume: skip pending bids, only\", remainingNow, \"ms left\");\n }\n } else {\n this.video.style.transition = \"none\";\n this.video.style.opacity = \"0\";\n this.video.style.visibility = \"hidden\";\n if (!this.config.singlePipelineMode) {\n this.showPlaceholderLayer();\n }\n this.adLayer.showPlaceholder();\n this.isInAdTransition = true;\n setTimeout(() => {\n this.isInAdTransition = false;\n if (!this.inAdBreak || bids.length === 0) return;\n const freshBids = this.pendingNextAdBids ?? bids;\n this.pendingNextAdBids = null;\n this.currentAdIndex++;\n this.adLayer.playAd(freshBids).catch((err) => {\n if (this.config.debugAdTiming) console.warn(\"[StormcloudVideoPlayer] playAd(pending) failed:\", err);\n this.handleAdFailure();\n });\n }, this.adTransitionGapMs);\n return;\n }\n }\n const remainingFinal = this.getRemainingAdMs();\n if (this.inAdBreak && remainingFinal > this.MIN_AD_REMAINING_MS) {\n if (this.config.debugAdTiming) {\n console.log(\"[StormcloudVideoPlayer] content_resume: ad ended/failed with time remaining, showing filler and continuing fetch for\", remainingFinal, \"ms\");\n }\n if (!this.config.disableFiller) {\n this.showPlaceholderLayer();\n this.adLayer.showPlaceholder();\n } else {\n this.video.style.transition = \"none\";\n this.video.style.opacity = \"0\";\n this.video.style.visibility = \"hidden\";\n this.adLayer.showPlaceholder();\n }\n this.continuousFetchingActive = true;\n this.startContinuousFetchLoop();\n return;\n }\n if (this.config.debugAdTiming) {\n console.log(\"[StormcloudVideoPlayer] content_resume: no more ads, ending ad pod\");\n }\n this.handleAdPodComplete();\n });\n }\n ensureFillerVideo() {\n if (this.fillerVideo) return;\n if (!this.video.parentElement) return;\n const filler = document.createElement(\"video\");\n filler.src = \"https://f000.backblazeb2.com/file/AdStormAds/384/Sonifi_Filler.mp4\";\n filler.loop = true;\n filler.muted = false;\n filler.playsInline = true;\n filler.style.position = \"absolute\";\n filler.style.left = \"0\";\n filler.style.top = \"0\";\n filler.style.width = \"100%\";\n filler.style.height = \"100%\";\n filler.style.objectFit = \"cover\";\n filler.style.zIndex = \"20\";\n filler.style.display = \"none\";\n filler.preload = \"auto\";\n this.video.parentElement.appendChild(filler);\n this.fillerVideo = filler;\n }\n showPlaceholderLayer() {\n if (this.config.disableFiller) return;\n this.ensureFillerVideo();\n if (!this.fillerVideo) return;\n if (!this.video.muted) {\n this.video.muted = true;\n this.video.volume = 0;\n }\n this.fillerVideo.style.display = \"block\";\n this.fillerVideo.play().catch(() => {\n if (this.fillerVideo) {\n this.fillerVideo.style.display = \"none\";\n }\n if (!this.adLayer.isAdPlaying()) {\n if (this.config.debugAdTiming) {\n console.log(\"[StormcloudVideoPlayer] Filler video failed \\u2014 restoring main video\");\n }\n this.adLayer.hidePlaceholder();\n if (this.video.paused && this.video.readyState >= 2) {\n this.video.play()?.catch(() => {\n });\n }\n }\n });\n if (this.config.debugAdTiming) {\n console.log(\"[StormcloudVideoPlayer] Showing filler video layer\");\n }\n }\n hidePlaceholderLayer() {\n if (!this.fillerVideo) return;\n this.fillerVideo.style.display = \"none\";\n this.fillerVideo.pause();\n this.fillerVideo.currentTime = 0;\n if (this.config.debugAdTiming) {\n console.log(\"[StormcloudVideoPlayer] Hiding filler video layer\");\n }\n }\n startFillerBreakTimer(durationMs) {\n this.stopFillerBreakTimer();\n this.showPlaceholderLayer();\n this.fillerBreakTimerId = setTimeout(() => {\n this.fillerBreakTimerId = void 0;\n this.hidePlaceholderLayer();\n if (this.inAdBreak) this.handleAdPodComplete();\n }, durationMs);\n }\n stopFillerBreakTimer() {\n if (this.fillerBreakTimerId !== void 0) {\n clearTimeout(this.fillerBreakTimerId);\n this.fillerBreakTimerId = void 0;\n }\n }\n attach() {\n if (this.attached) return;\n this.attached = true;\n this.video.autoplay = !!this.config.autoplay;\n this.video.muted = !!this.config.muted;\n if (!this.config.disableAds) {\n this.initializeAdLayer();\n }\n this.timeUpdateHandler = () => {\n this.onTimeUpdate(this.video.currentTime);\n };\n this.video.addEventListener(\"timeupdate\", this.timeUpdateHandler);\n this.emptiedHandler = () => {\n if (this.nativeHlsMode && this.videoSrcProtection && !this.adLayer.isAdPlaying()) {\n if (this.config.debugAdTiming) {\n console.log(\n \"[StormcloudVideoPlayer] Video src was cleared, restoring:\",\n this.videoSrcProtection\n );\n }\n const currentTime = this.video.currentTime;\n const wasPaused = this.video.paused;\n this.video.src = this.videoSrcProtection;\n this.video.currentTime = currentTime;\n if (!wasPaused) {\n this.video.play().catch(() => {\n });\n }\n }\n };\n this.video.addEventListener(\"emptied\", this.emptiedHandler);\n }\n shouldUseNativeHls() {\n const streamType = this.getStreamType();\n if (streamType === \"other\") {\n return true;\n }\n const canNative = this.video.canPlayType(\"application/vnd.apple.mpegurl\");\n return !!(this.config.allowNativeHls && canNative);\n }\n initializeTracking() {\n sendInitialTracking(this.config.licenseKey).then(() => {\n this.heartbeatInterval = window.setInterval(() => {\n this.sendHeartbeatIfNeeded();\n }, 5e3);\n }).catch((error) => {\n if (this.config.debugAdTiming) {\n console.warn(\n \"[StormcloudVideoPlayer] Failed to send initial tracking:\",\n error\n );\n }\n this.heartbeatInterval = window.setInterval(() => {\n this.sendHeartbeatIfNeeded();\n }, 5e3);\n });\n }\n sendHeartbeatIfNeeded() {\n const now = Date.now();\n if (!this.lastHeartbeatTime || now - this.lastHeartbeatTime > 3e4) {\n this.lastHeartbeatTime = now;\n sendHeartbeat(this.config.licenseKey).catch((error) => {\n if (this.config.debugAdTiming) {\n console.warn(\n \"[StormcloudVideoPlayer] Failed to send heartbeat:\",\n error\n );\n }\n });\n }\n }\n getCurrentAdIndex() {\n return this.currentAdIndex;\n }\n getTotalAdsInBreak() {\n return this.totalAdsInBreak;\n }\n getRemainingAdSeconds() {\n const remainingMs = this.getRemainingAdMs();\n if (!Number.isFinite(remainingMs) || remainingMs <= 0 || remainingMs === Number.MAX_SAFE_INTEGER) {\n return 0;\n }\n return Math.ceil(remainingMs / 1e3);\n }\n isAdPlaying() {\n return this.inAdBreak && this.adLayer.isAdPlaying();\n }\n isShowingAds() {\n return this.showAds;\n }\n isInAdBreak() {\n return this.inAdBreak;\n }\n initializeAdLayer() {\n if (this.adLayerInitialized) return;\n this.adLayer.initialize();\n if (!this.config.disableFiller) {\n this.ensureFillerVideo();\n }\n this.adLayer.updateOriginalMutedState(this.video.muted, this.video.volume);\n this.attachAdLayerEventListeners();\n this.adLayerInitialized = true;\n }\n setDisableAds(disabled) {\n this.config.disableAds = disabled;\n if (!disabled && this.attached) {\n this.initializeAdLayer();\n }\n if (this.config.debugAdTiming) {\n console.log(\"[StormcloudVideoPlayer] setDisableAds:\", disabled);\n }\n }\n syncMainContentAudioWhenVisible() {\n const adLayerShowing = this.showAds || this.adLayer.isAdPlaying();\n if (adLayerShowing) return;\n const muted = this.adLayer.getOriginalMutedState();\n const volume = this.adLayer.getOriginalVolume();\n if (this.video.muted !== muted) this.video.muted = muted;\n if (Math.abs(this.video.volume - volume) > 0.01) this.video.volume = volume;\n }\n getStreamType() {\n const url = this.config.src.toLowerCase();\n if (url.includes(\".m3u8\") || url.includes(\"/hls/\") || url.includes(\"application/vnd.apple.mpegurl\")) {\n return \"hls\";\n }\n return \"other\";\n }\n shouldShowNativeControls() {\n const streamType = this.getStreamType();\n if (streamType === \"other\") {\n return !(this.config.showCustomControls ?? false);\n }\n return !!(this.config.allowNativeHls && !(this.config.showCustomControls ?? false));\n }\n shouldContinueLiveStreamDuringAds() {\n if (this.config.allowNativeHls) {\n return false;\n }\n if (!this.isLiveStream) {\n return false;\n }\n if (this.config.singlePipelineMode) {\n return false;\n }\n const browser = detectBrowser();\n if (browser.isSmartTV) {\n return false;\n }\n return true;\n }\n startAdPrefetch(durationSeconds, fragmentSn) {\n if (this.config.disableAds) return;\n if (this.pendingAdBreak || this.inAdBreak) {\n return;\n }\n this.pendingAdBreak = {\n ...durationSeconds !== void 0 ? { durationSeconds } : {},\n ...fragmentSn !== void 0 ? { detectedAtFragmentSn: fragmentSn } : {},\n isFetching: false,\n fetchStartTime: Date.now()\n };\n void this.runAdPrefetch(durationSeconds);\n if (this.config.debugAdTiming) {\n console.log(\"[PREFETCH] Ad break registered, multi-ad prefetch started\");\n }\n }\n async runAdPrefetch(durationSeconds) {\n const durSec = durationSeconds ?? 60;\n const context = {\n breakDurationSec: durSec,\n remainingBreakSec: durSec\n };\n let firstBids;\n try {\n firstBids = await this.adRequest({ ...context, adIndex: 1 });\n } catch {\n firstBids = [];\n }\n if (this.inAdBreak) return;\n if (firstBids.length === 0) {\n if (this.config.debugAdTiming) {\n console.log(\"[PREFETCH] First VAST request returned no ad, aborting prefetch\");\n }\n this.clearPendingAdBreak();\n return;\n }\n const adDurationSec = firstBids[0]?.durationSec ?? 30;\n const estimatedCount = Math.max(1, Math.ceil(durSec / adDurationSec));\n if (this.config.debugAdTiming) {\n console.log(\n `[PREFETCH] Ad duration=${adDurationSec}s, break=${durSec}s \\u2192 ${estimatedCount} ad(s) needed`\n );\n }\n const firstToken = `preload_${Date.now()}_${Math.random().toString(36).slice(2, 7)}`;\n try {\n await this.adLayer.preloadAd(firstBids, firstToken);\n if (!this.inAdBreak) {\n this.preloadedTokens.push(firstToken);\n if (this.config.debugAdTiming) {\n console.log(`[PREFETCH] First ad preloaded and queued, token=${firstToken}`);\n }\n }\n } catch {\n if (this.config.debugAdTiming) {\n console.warn(`[PREFETCH] First ad preload failed, token=${firstToken}`);\n }\n }\n if (estimatedCount > 1) {\n const remaining = Array.from(\n { length: estimatedCount - 1 },\n (_, i) => this.adRequest({ ...context, adIndex: i + 2 }).then((bids) => ({ ok: true, value: bids })).catch(() => ({ ok: false }))\n );\n const results = await Promise.all(remaining);\n for (const result of results) {\n if (this.inAdBreak) break;\n if (result.ok && result.value.length > 0) {\n const token = `preload_${Date.now()}_${Math.random().toString(36).slice(2, 7)}`;\n try {\n await this.adLayer.preloadAd(result.value, token);\n if (!this.inAdBreak) {\n this.preloadedTokens.push(token);\n if (this.config.debugAdTiming) {\n console.log(`[PREFETCH] Additional ad preloaded and queued, token=${token}`);\n }\n }\n } catch {\n if (this.config.debugAdTiming) {\n console.warn(`[PREFETCH] Additional ad preload failed, token=${token}`);\n }\n }\n }\n }\n }\n if (this.config.debugAdTiming) {\n console.log(`[PREFETCH] Pre-fetch complete: ${this.preloadedTokens.length} ad(s) queued`);\n }\n }\n clearPendingAdBreak() {\n if (this.prefetchTimerId != null) {\n clearTimeout(this.prefetchTimerId);\n this.prefetchTimerId = void 0;\n }\n this.pendingAdBreak = null;\n }\n cancelAndClearPreloadedTokens() {\n for (const token of this.preloadedTokens) {\n this.adLayer.cancelPreload(token);\n }\n this.preloadedTokens = [];\n }\n startAdInsertionPolling() {\n if (this.adInsertionPollingId != null) return;\n this.fetchAdInsertionPoint();\n this.adInsertionPollingId = window.setInterval(() => {\n this.fetchAdInsertionPoint();\n }, 1e3);\n }\n stopAdInsertionPolling() {\n if (this.adInsertionPollingId != null) {\n clearInterval(this.adInsertionPollingId);\n this.adInsertionPollingId = void 0;\n }\n }\n async fetchAdInsertionPoint() {\n if (!this.config.projectId) return;\n try {\n const resp = await fetch(\n `https://adstorm.co/api-adstorm-dev/adstorm/adcision/channels/${encodeURIComponent(this.config.projectId)}/ad-insertion-point`\n );\n if (!resp.ok) return;\n const data = await resp.json();\n const prevSegment = this.lastAdInsertionPoint?.segment_ts_name;\n const isNew = data.updated_at !== this.lastAdInsertionPoint?.updated_at;\n const segmentChanged = prevSegment !== data.segment_ts_name;\n this.lastAdInsertionPoint = data;\n if (isNew) {\n this.pushAdInsertionDebug(\"api_response\", data.segment_ts_name, {\n offsetSeconds: data.offset_seconds,\n updatedAt: data.updated_at,\n detail: `ch=${data.channel_id}`\n });\n if (segmentChanged && (this.pendingAdBreak || this.adInsertionOffsetTimerId != null)) {\n this.clearAdInsertionOffsetTimer();\n this.clearPendingAdBreak();\n this.cancelAndClearPreloadedTokens();\n if (this.config.debugAdTiming) {\n console.log(\n `[StormcloudVideoPlayer] Insertion segment changed (${prevSegment} \\u2192 ${data.segment_ts_name}), stale pending state cleared`\n );\n }\n }\n this.checkAdInsertionInManifest();\n }\n if (this.config.debugAdTiming) {\n console.log(\"[StormcloudVideoPlayer] Ad insertion point API response:\", data);\n }\n } catch {\n if (this.config.debugAdTiming) {\n console.warn(\"[StormcloudVideoPlayer] Ad insertion point API fetch failed\");\n }\n }\n }\n checkAdInsertionInManifest() {\n if (!this.lastAdInsertionPoint) return;\n if (this.inAdBreak || this.pendingAdBreak) return;\n if (this.lastAdInsertionPoint.updated_at === this.processedAdInsertionUpdatedAt) return;\n const segmentName = this.lastAdInsertionPoint.segment_ts_name;\n const levels = this.hls?.levels;\n if (!levels) return;\n for (const level of levels) {\n const fragments = level.details?.fragments;\n if (!Array.isArray(fragments)) continue;\n for (const frag of fragments) {\n if (this.fragmentMatchesSegment(frag, segmentName)) {\n const currentTime = this.video.currentTime;\n const fragStart = frag.start ?? 0;\n const fragDuration = frag.duration ?? 0;\n const isCurrentlyPlaying = fragDuration > 0 && currentTime >= fragStart && currentTime < fragStart + fragDuration;\n this.pushAdInsertionDebug(\"segment_found\", segmentName, {\n detail: `sn=${frag?.sn ?? \"?\"} ${isCurrentlyPlaying ? \"(playing)\" : \"(future)\"}`\n });\n if (this.config.debugAdTiming) {\n console.log(\n `[StormcloudVideoPlayer] Ad insertion segment \"${segmentName}\" found in manifest \\u2014 ` + (isCurrentlyPlaying ? \"currently playing, scheduling directly\" : \"starting pre-fetch\")\n );\n }\n this.startAdPrefetch(60, frag?.sn);\n if (isCurrentlyPlaying && !this.inAdBreak) {\n this.processedAdInsertionUpdatedAt = this.lastAdInsertionPoint.updated_at;\n const rawOffsetMs = (this.lastAdInsertionPoint.offset_seconds ?? 0) * 1e3;\n const elapsedInFragMs = (currentTime - fragStart) * 1e3;\n const remainingOffsetMs = Math.max(0, rawOffsetMs - elapsedInFragMs);\n this.pushAdInsertionDebug(\"segment_playing\", segmentName, {\n offsetSeconds: this.lastAdInsertionPoint.offset_seconds,\n detail: `sn=${frag?.sn ?? \"?\"} (caught in manifest check)`\n });\n this.pushAdInsertionDebug(\"ad_scheduled\", segmentName, {\n offsetSeconds: this.lastAdInsertionPoint.offset_seconds,\n detail: `in ${remainingOffsetMs}ms (adjusted for elapsed ${Math.round(elapsedInFragMs)}ms)`\n });\n this.clearAdInsertionOffsetTimer();\n this.adInsertionOffsetTimerId = window.setTimeout(() => {\n this.adInsertionOffsetTimerId = void 0;\n if (this.inAdBreak) return;\n this.pushAdInsertionDebug(\"ad_triggered\", segmentName, {\n detail: \"ad break started (60s, via manifest-check path)\"\n });\n void this.handleAdStart(60);\n }, remainingOffsetMs);\n }\n return;\n }\n }\n }\n }\n extractTsFilename(url) {\n const clean = url.includes(\"?\") ? url.slice(0, url.indexOf(\"?\")) : url;\n const parts = clean.split(\"/\");\n return parts[parts.length - 1] ?? clean;\n }\n fragmentMatchesSegment(frag, segmentName) {\n const rawUrl = frag?.url || frag?.relurl || \"\";\n if (!rawUrl) return false;\n return this.extractTsFilename(rawUrl) === this.extractTsFilename(segmentName);\n }\n clearAdInsertionOffsetTimer() {\n if (this.adInsertionOffsetTimerId != null) {\n clearTimeout(this.adInsertionOffsetTimerId);\n this.adInsertionOffsetTimerId = void 0;\n }\n }\n startContinuousFetchLoop() {\n if (this.continuousFetchLoopPromise != null) return;\n this.continuousFetchLoopPromise = this.runContinuousFetchLoop();\n }\n async runContinuousFetchLoop() {\n const backoffMs = () => {\n const mult = Math.pow(2, this.consecutiveFailures);\n return Math.min(this.backoffBaseMs * mult, this.maxBackoffMs);\n };\n while (this.inAdBreak && this.continuousFetchingActive) {\n if (this.consecutiveFailures >= this.maxConsecutiveFailures) break;\n if (this.totalAdRequestsInBreak >= this.maxTotalAdRequestsPerBreak) break;\n if (this.adLayer.isAdPlaying() || this.isInAdTransition) {\n if (this.pendingNextAdBids == null) {\n try {\n const remaining = this.getRemainingAdMs();\n const prefetchContext = this.expectedAdBreakDurationMs != null ? {\n breakDurationSec: this.expectedAdBreakDurationMs / 1e3,\n remainingBreakSec: remaining / 1e3,\n adIndex: this.currentAdIndex + 1\n } : void 0;\n if (this.config.debugAdTiming) {\n console.log(\"[CONTINUOUS-FETCH] Pre-fetching next ad during playback, remaining:\", remaining, \"ms\");\n }\n const bids = await this.adRequest(prefetchContext);\n this.lastAdRequestTime = Date.now();\n if (!this.inAdBreak) break;\n if (bids.length > 0) {\n this.consecutiveFailures = 0;\n this.pendingNextAdBids = bids;\n this.totalAdsInBreak = Math.max(\n this.totalAdsInBreak,\n this.currentAdIndex + this.preloadedTokens.length + 1\n );\n if (this.config.debugAdTiming) {\n console.log(\"[CONTINUOUS-FETCH] Pre-fetched next ad stored as pending\");\n }\n } else {\n this.consecutiveFailures++;\n }\n } catch (err) {\n this.consecutiveFailures++;\n if (this.config.debugAdTiming) {\n console.warn(\"[CONTINUOUS-FETCH] Pre-fetch adRequest failed:\", err);\n }\n }\n } else {\n await new Promise((r) => setTimeout(r, 200));\n }\n continue;\n }\n if (this.pendingNextAdBids != null && this.pendingNextAdBids.length > 0) {\n const bids = this.pendingNextAdBids;\n this.pendingNextAdBids = null;\n const remainingNow = this.getRemainingAdMs();\n if (this.expectedAdBreakDurationMs == null || remainingNow >= this.MIN_AD_REMAINING_MS) {\n this.currentAdIndex++;\n if (this.config.licenseKey) {\n sendAdLoadedTracking(this.config.licenseKey, {\n source: this.getAdSource(),\n timestamp: (/* @__PURE__ */ new Date()).toISOString()\n });\n }\n await this.adLayer.playAd(bids);\n if (this.expectedAdBreakDurationMs != null && this.adStopTimerId == null) {\n this.scheduleAdStopCountdown(this.getRemainingAdMs());\n }\n this.adLayer.setAdVolume(\n this.adLayer.getOriginalMutedState() ? 1 : this.adLayer.getOriginalVolume()\n );\n } else if (this.config.debugAdTiming) {\n console.log(\"[CONTINUOUS-FETCH] Discarding pre-fetched bids: only\", remainingNow, \"ms left\");\n }\n continue;\n }\n const urgentNeedAd = this.inAdBreak && !this.adLayer.isAdPlaying();\n const delay = this.lastAdRequestTime ? this.minAdRequestIntervalMs + (!urgentNeedAd && this.consecutiveFailures > 0 ? backoffMs() : 0) : 0;\n const elapsed = Date.now() - this.lastAdRequestTime;\n if (elapsed < delay && this.lastAdRequestTime > 0) {\n await new Promise((r) => setTimeout(r, delay - elapsed));\n }\n if (!this.inAdBreak || !this.continuousFetchingActive) break;\n try {\n const remaining = this.getRemainingAdMs();\n const context = this.expectedAdBreakDurationMs != null ? {\n breakDurationSec: this.expectedAdBreakDurationMs / 1e3,\n remainingBreakSec: remaining / 1e3,\n adIndex: this.currentAdIndex + 1\n } : void 0;\n const bids = await this.adRequest(context);\n this.lastAdRequestTime = Date.now();\n if (!this.inAdBreak) break;\n if (bids.length > 0) {\n this.consecutiveFailures = 0;\n if (this.adLayer.isAdPlaying() || this.isInAdTransition) {\n this.pendingNextAdBids = bids;\n this.totalAdsInBreak = Math.max(\n this.totalAdsInBreak,\n this.currentAdIndex + this.preloadedTokens.length + 1\n );\n if (this.config.debugAdTiming) {\n console.log(\"[CONTINUOUS-FETCH] Next ad response stored (ad currently playing or in transition)\");\n }\n } else {\n const remainingNow = this.getRemainingAdMs();\n if (this.expectedAdBreakDurationMs != null && remainingNow < this.MIN_AD_REMAINING_MS) {\n if (this.config.debugAdTiming) {\n console.log(\"[CONTINUOUS-FETCH] Skipping ad from loop: only\", remainingNow, \"ms left\");\n }\n } else {\n this.currentAdIndex++;\n if (this.config.licenseKey) {\n sendAdLoadedTracking(this.config.licenseKey, {\n source: this.getAdSource(),\n timestamp: (/* @__PURE__ */ new Date()).toISOString()\n });\n }\n await this.adLayer.playAd(bids);\n if (this.expectedAdBreakDurationMs != null && this.adStopTimerId == null) {\n this.scheduleAdStopCountdown(this.getRemainingAdMs());\n }\n this.adLayer.setAdVolume(\n this.adLayer.getOriginalMutedState() ? 1 : this.adLayer.getOriginalVolume()\n );\n }\n }\n } else {\n this.consecutiveFailures++;\n }\n } catch (err) {\n this.consecutiveFailures++;\n if (this.config.debugAdTiming) {\n console.warn(\"[CONTINUOUS-FETCH] adRequest failed:\", err);\n }\n }\n const sleepMs = this.inAdBreak && !this.adLayer.isAdPlaying() ? 0 : backoffMs();\n await new Promise((r) => setTimeout(r, sleepMs));\n }\n this.continuousFetchLoopPromise = null;\n }\n async handleAdStart(durationSeconds) {\n const adBreakDurationMs = durationSeconds != null ? durationSeconds * 1e3 : void 0;\n if (this.config.debugAdTiming) {\n const mode = this.isLiveStream ? \"LIVE\" : \"VOD\";\n console.log(\n `[CONTINUOUS-FETCH] \\u{1F4FA} ${mode} MODE: Target duration=${adBreakDurationMs}ms`\n );\n }\n this.consecutiveFailures = 0;\n this.continuousFetchingActive = true;\n this.continuousFetchLoopPromise = null;\n this.pendingNextAdBids = null;\n this.isShowingPlaceholder = false;\n this.totalAdRequestsInBreak = 0;\n if (this.savedMutedStateBeforeAd == null && !this.video.muted) {\n this.savedMutedStateBeforeAd = {\n muted: false,\n volume: this.video.volume\n };\n }\n const state = this.savedMutedStateBeforeAd ?? {\n muted: this.video.muted,\n volume: this.video.volume\n };\n this.adLayer.updateOriginalMutedState(state.muted, state.volume);\n if (!this.config.disableFiller && !this.video.muted) {\n this.video.muted = true;\n this.video.volume = 0;\n if (this.config.debugAdTiming) {\n console.log(\"[StormcloudVideoPlayer] Muted video in handleAdStart\");\n }\n }\n this.inAdBreak = true;\n this.currentAdBreakStartWallClockMs = Date.now();\n this.currentAdIndex = 0;\n this.totalAdsInBreak = Math.max(1, this.preloadedTokens.length);\n this.adPodQueue = [];\n if (!this.config.disableFiller) this.showAds = true;\n if (adBreakDurationMs != null) {\n this.startFillerBreakTimer(adBreakDurationMs);\n } else if (!this.config.disableFiller && this.preloadedTokens.length === 0) {\n this.showPlaceholderLayer();\n }\n if (!this.config.disableFiller) this.adLayer.showPlaceholder();\n if (this.expectedAdBreakDurationMs == null && adBreakDurationMs != null) {\n this.expectedAdBreakDurationMs = adBreakDurationMs;\n }\n if (this.expectedAdBreakDurationMs != null) {\n this.scheduleAdStopCountdown(this.expectedAdBreakDurationMs);\n }\n this.clearPendingAdBreak();\n const adBreakToken = Date.now();\n this.activeAdRequestToken = adBreakToken;\n this.startAdFailsafeTimer(adBreakToken);\n this.startAdRequestWatchdog(adBreakToken);\n const adVolume = state.muted ? 1 : state.volume;\n if (this.preloadedTokens.length > 0) {\n const token = this.preloadedTokens.shift();\n if (this.config.debugAdTiming) {\n console.log(\"[CONTINUOUS-FETCH] \\u2705 Playing pre-buffered ad, token=\", token);\n }\n const remaining = this.getRemainingAdMs();\n if (this.expectedAdBreakDurationMs == null || remaining >= this.MIN_AD_REMAINING_MS) {\n this.currentAdIndex++;\n if (this.config.licenseKey) {\n sendAdLoadedTracking(this.config.licenseKey, {\n source: this.getAdSource(),\n timestamp: (/* @__PURE__ */ new Date()).toISOString()\n });\n }\n try {\n await this.adLayer.playPreloaded(token);\n if (this.expectedAdBreakDurationMs != null && this.adStopTimerId == null) {\n this.scheduleAdStopCountdown(this.getRemainingAdMs());\n }\n this.adLayer.setAdVolume(adVolume);\n } catch (err) {\n if (this.config.debugAdTiming) console.warn(\"[CONTINUOUS-FETCH] playPreloaded failed:\", err);\n this.consecutiveFailures++;\n await this.showPlaceholderAndWaitForAds();\n }\n } else {\n if (this.config.debugAdTiming) {\n console.log(\"[CONTINUOUS-FETCH] Skipping ad: only\", remaining, \"ms left in break\");\n }\n this.adLayer.cancelPreload(token);\n await this.showPlaceholderAndWaitForAds();\n }\n }\n this.startContinuousFetchLoop();\n }\n stopContinuousFetching() {\n this.continuousFetchingActive = false;\n if (this.config.debugAdTiming) {\n console.log(\"[CONTINUOUS-FETCH] \\u{1F6D1} Stopping continuous ad fetching\");\n }\n }\n async tryNextAvailableAdWithRateLimit() {\n if (this.consecutiveFailures >= this.maxConsecutiveFailures) {\n if (this.config.debugAdTiming) {\n console.log(`[CONTINUOUS-FETCH] \\u{1F6D1} Too many consecutive failures (${this.consecutiveFailures}), ending ad break gracefully`);\n }\n this.handleAdPodComplete();\n return;\n }\n const backoffMultiplier = Math.pow(2, this.consecutiveFailures);\n const backoffDelay = Math.min(this.backoffBaseMs * backoffMultiplier, this.maxBackoffMs);\n const effectiveMinInterval = this.minAdRequestIntervalMs + (this.consecutiveFailures > 0 ? backoffDelay : 0);\n const timeSinceLastRequest = Date.now() - this.lastAdRequestTime;\n if (timeSinceLastRequest < effectiveMinInterval) {\n const waitTime = effectiveMinInterval - timeSinceLastRequest;\n if (this.config.debugAdTiming) {\n console.log(`[CONTINUOUS-FETCH] \\u23F3 Rate limiting: waiting ${waitTime}ms before next request (backoff: ${this.consecutiveFailures} failures)`);\n }\n await new Promise((resolve) => setTimeout(resolve, waitTime));\n }\n return this.tryNextAvailableAd(0);\n }\n async tryNextAvailableAd(_retryCount = 0) {\n if (this.totalAdRequestsInBreak >= this.maxTotalAdRequestsPerBreak) {\n if (this.config.debugAdTiming) {\n console.log(`[CONTINUOUS-FETCH] \\u{1F6D1} Max ad requests per break (${this.maxTotalAdRequestsPerBreak}) reached`);\n }\n this.handleAdPodComplete();\n return;\n }\n const remaining = this.getRemainingAdMs();\n if (remaining <= 500 && this.expectedAdBreakDurationMs != null) {\n if (this.config.debugAdTiming) {\n console.log(\"[CONTINUOUS-FETCH] \\u23F9\\uFE0F No time remaining, ending ad break\");\n }\n this.handleAdPodComplete();\n return;\n }\n if (this.consecutiveFailures >= this.maxConsecutiveFailures) {\n if (this.config.debugAdTiming) {\n console.log(`[CONTINUOUS-FETCH] \\u{1F6D1} Too many consecutive failures (${this.consecutiveFailures}), ending ad break`);\n }\n this.handleAdPodComplete();\n return;\n }\n try {\n this.lastAdRequestTime = Date.now();\n const bids = await this.adRequest();\n if (!this.inAdBreak) return;\n if (bids.length > 0) {\n this.consecutiveFailures = 0;\n this.currentAdIndex++;\n this.totalAdRequestsInBreak++;\n if (this.adLayer.isAdPlaying() || this.isInAdTransition) {\n this.pendingNextAdBids = bids;\n this.totalAdsInBreak = Math.max(\n this.totalAdsInBreak,\n this.currentAdIndex + this.preloadedTokens.length\n );\n } else {\n if (this.config.licenseKey) {\n sendAdLoadedTracking(this.config.licenseKey, {\n source: this.getAdSource(),\n timestamp: (/* @__PURE__ */ new Date()).toISOString()\n });\n }\n await this.adLayer.playAd(bids);\n if (this.expectedAdBreakDurationMs != null && this.adStopTimerId == null) {\n this.scheduleAdStopCountdown(this.getRemainingAdMs());\n }\n this.adLayer.setAdVolume(\n this.adLayer.getOriginalMutedState() ? 1 : this.adLayer.getOriginalVolume()\n );\n }\n } else {\n this.consecutiveFailures++;\n await this.showPlaceholderAndWaitForAds();\n }\n } catch (error) {\n this.consecutiveFailures++;\n if (this.config.debugAdTiming) {\n console.warn(\"[CONTINUOUS-FETCH] tryNextAvailableAd request failed:\", error);\n }\n await this.showPlaceholderAndWaitForAds();\n }\n }\n async showPlaceholderAndWaitForAds() {\n const remaining = this.getRemainingAdMs();\n const waitTime = Math.min(this.maxPlaceholderDurationMs, remaining);\n if (this.consecutiveFailures >= this.maxConsecutiveFailures) {\n const stillRemaining2 = this.getRemainingAdMs();\n if (stillRemaining2 >= 1e3) {\n if (this.config.debugAdTiming) {\n console.log(\"[CONTINUOUS-FETCH] \\u{1F6D1} Max failures reached but break still active \\u2014 resetting and continuing filler\");\n }\n this.consecutiveFailures = 0;\n return;\n }\n if (this.config.debugAdTiming) {\n console.log(\"[CONTINUOUS-FETCH] \\u{1F6D1} Skipping placeholder - too many consecutive failures\");\n }\n this.handleAdPodComplete();\n return;\n }\n if (waitTime < 1e3) {\n this.handleAdPodComplete();\n return;\n }\n if (this.config.debugAdTiming) {\n console.log(`[CONTINUOUS-FETCH] \\u2B1B Showing placeholder for ${waitTime}ms while waiting for ad response`);\n }\n if (!this.config.disableFiller) {\n this.isShowingPlaceholder = true;\n this.showPlaceholderLayer();\n this.adLayer.showPlaceholder();\n }\n const checkInterval = 300;\n const maxChecks = Math.floor(waitTime / checkInterval);\n for (let i = 0; i < maxChecks; i++) {\n await new Promise((resolve) => setTimeout(resolve, checkInterval));\n if (!this.inAdBreak) return;\n if (this.consecutiveFailures >= this.maxConsecutiveFailures) {\n if (this.config.debugAdTiming) {\n console.log(\"[CONTINUOUS-FETCH] \\u{1F6D1} Too many failures during placeholder wait \\u2014 resetting and continuing filler\");\n }\n this.consecutiveFailures = 0;\n break;\n }\n if (this.pendingNextAdBids != null && this.pendingNextAdBids.length > 0) {\n const bids = this.pendingNextAdBids;\n this.pendingNextAdBids = null;\n this.isShowingPlaceholder = false;\n this.adLayer.hidePlaceholder();\n this.currentAdIndex++;\n try {\n await this.adLayer.playAd(bids);\n this.consecutiveFailures = 0;\n } catch {\n this.consecutiveFailures++;\n await this.tryNextAvailableAdWithRateLimit();\n }\n return;\n }\n if (this.adLayer.isAdPlaying()) {\n this.isShowingPlaceholder = false;\n this.adLayer.hidePlaceholder();\n return;\n }\n }\n const stillRemaining = this.getRemainingAdMs();\n if (stillRemaining >= 1e3) {\n if (this.config.debugAdTiming) {\n console.log(`[CONTINUOUS-FETCH] \\u23F0 Placeholder slot expired, ${stillRemaining}ms still remaining \\u2014 continuing filler`);\n }\n this.isShowingPlaceholder = false;\n this.adLayer.hidePlaceholder();\n this.consecutiveFailures = 0;\n return;\n }\n if (this.config.debugAdTiming) {\n console.log(\"[CONTINUOUS-FETCH] \\u23F0 Placeholder timeout, ending ad break\");\n }\n this.isShowingPlaceholder = false;\n this.adLayer.hidePlaceholder();\n this.handleAdPodComplete();\n }\n onTimeUpdate(_currentTimeSec) {\n if (this.adLayer.isAdPlaying()) return;\n }\n scheduleAdStopCountdown(remainingMs) {\n this.clearAdStopTimer();\n const ms = Math.max(0, Math.floor(remainingMs));\n if (ms === 0) {\n this.ensureAdStoppedByTimer();\n return;\n }\n this.adStopTimerId = window.setTimeout(() => {\n this.ensureAdStoppedByTimer();\n }, ms);\n }\n clearAdStopTimer() {\n if (this.adStopTimerId != null) {\n clearTimeout(this.adStopTimerId);\n this.adStopTimerId = void 0;\n }\n }\n ensureAdStoppedByTimer() {\n if (!this.inAdBreak) return;\n this.adStopTimerId = void 0;\n const adPlaying = this.adLayer.isAdPlaying();\n const pendingAds = this.adPodQueue.length > 0;\n const checkIntervalMs = Math.max(\n 250,\n Math.floor(this.config.adBreakCheckIntervalMs ?? 1e3)\n );\n const maxExtensionMsConfig = this.config.maxAdBreakExtensionMs;\n const maxExtensionMs = typeof maxExtensionMsConfig === \"number\" && maxExtensionMsConfig > 0 ? maxExtensionMsConfig : 6e4;\n let elapsedSinceStartMs = 0;\n if (this.currentAdBreakStartWallClockMs != null) {\n elapsedSinceStartMs = Date.now() - this.currentAdBreakStartWallClockMs;\n }\n const expectedDurationMs = this.expectedAdBreakDurationMs ?? 0;\n const overrunMs = Math.max(0, elapsedSinceStartMs - expectedDurationMs);\n const shouldExtendAdBreak = (adPlaying || pendingAds || this.showAds) && overrunMs < maxExtensionMs;\n if (shouldExtendAdBreak) {\n this.scheduleAdStopCountdown(checkIntervalMs);\n return;\n }\n if (adPlaying) {\n this.adLayer.stop().catch(() => {\n });\n }\n this.handleAdPodComplete();\n }\n handleAdPodComplete() {\n if (this.config.debugAdTiming) {\n console.log(\"[StormcloudVideoPlayer] \\u{1F3C1} Ad pod complete - cleaning up\");\n }\n this.clearAdRequestWatchdog();\n this.clearAdFailsafeTimer();\n this.clearAdInsertionOffsetTimer();\n this.activeAdRequestToken = null;\n this.isInAdTransition = false;\n this.stopContinuousFetching();\n this.stopFillerBreakTimer();\n this.hidePlaceholderLayer();\n this.clearPendingAdBreak();\n this.cancelAndClearPreloadedTokens();\n this.pendingNextAdBids = null;\n if (this.isShowingPlaceholder) {\n this.adLayer.hidePlaceholder();\n this.isShowingPlaceholder = false;\n }\n this.inAdBreak = false;\n this.expectedAdBreakDurationMs = void 0;\n this.currentAdBreakStartWallClockMs = void 0;\n this.clearAdStopTimer();\n this.adPodQueue = [];\n this.showAds = false;\n this.currentAdIndex = 0;\n this.totalAdsInBreak = 0;\n this.totalAdRequestsInBreak = 0;\n this.consecutiveFailures = 0;\n const restoredMuted = this.savedMutedStateBeforeAd?.muted ?? this.adLayer.getOriginalMutedState();\n const restoredVolume = this.savedMutedStateBeforeAd?.volume ?? this.adLayer.getOriginalVolume();\n this.adLayer.updateOriginalMutedState(restoredMuted, restoredVolume);\n this.adLayer.stop().catch(() => {\n });\n if (this.video.muted !== restoredMuted) {\n this.video.muted = restoredMuted;\n }\n if (Math.abs(this.video.volume - restoredVolume) > 0.01) {\n this.video.volume = restoredVolume;\n }\n const browser = detectBrowser();\n const isSmartTV = browser.tizenVersion !== void 0 || browser.webOSVersion !== void 0 || !!this.config.singlePipelineMode;\n if (isSmartTV && this.hls) {\n const hlsRef = this.hls;\n const savedMuted = restoredMuted;\n const savedVolume = restoredVolume;\n const videoRef = this.video;\n const debugEnabled = this.config.debugAdTiming;\n const tryPlay = (attempt) => {\n if (this.inAdBreak || this.adLayer.isAdPlaying()) return;\n videoRef.play()?.catch(() => {\n if (attempt < 3) {\n if (debugEnabled) {\n console.log(`[StormcloudVideoPlayer] Smart TV: play() retry ${attempt + 1}/3 in ${500 * (attempt + 1)}ms`);\n }\n setTimeout(() => tryPlay(attempt + 1), 500 * (attempt + 1));\n }\n });\n };\n const onManifestParsedRestore = () => {\n hlsRef.off(import_hls.default.Events.MANIFEST_PARSED, onManifestParsedRestore);\n if (!this.inAdBreak && !this.adLayer.isAdPlaying()) {\n if (videoRef.muted !== savedMuted) videoRef.muted = savedMuted;\n if (Math.abs(videoRef.volume - savedVolume) > 0.01) videoRef.volume = savedVolume;\n if (debugEnabled) {\n console.log(\"[StormcloudVideoPlayer] Smart TV: audio state restored on MANIFEST_PARSED after re-attach\");\n }\n hlsRef.startLoad(-1);\n if (debugEnabled) {\n console.log(\"[StormcloudVideoPlayer] Smart TV: seeking to live edge and resuming playback after re-attach\");\n }\n }\n };\n hlsRef.on(import_hls.default.Events.MANIFEST_PARSED, onManifestParsedRestore);\n const pipelineDelayMs = 300;\n if (debugEnabled) {\n console.log(`[StormcloudVideoPlayer] Smart TV: waiting ${pipelineDelayMs}ms for hardware pipeline release before re-attach`);\n }\n setTimeout(() => {\n if (this.inAdBreak || this.adLayer.isAdPlaying()) return;\n if (this.hls) {\n this.hls.attachMedia(this.video);\n if (debugEnabled) {\n console.log(\"[StormcloudVideoPlayer] Smart TV: re-attached HLS to video element after ad break to restore media pipeline\");\n }\n }\n }, pipelineDelayMs);\n } else {\n if (this.shouldContinueLiveStreamDuringAds()) {\n if (this.config.debugAdTiming) {\n if (this.video.paused) {\n console.log(\"[StormcloudVideoPlayer] Content video paused in live mode after ads, resuming playback\");\n } else {\n console.log(\"[StormcloudVideoPlayer] Content video already playing in live mode after ads\");\n }\n }\n this.video.play()?.catch(() => {\n });\n } else if (this.video.paused) {\n this.video.play()?.catch(() => {\n });\n }\n }\n this.syncMainContentAudioWhenVisible();\n if (!restoredMuted) {\n requestAnimationFrame(() => {\n this.syncMainContentAudioWhenVisible();\n });\n setTimeout(() => {\n this.syncMainContentAudioWhenVisible();\n }, 0);\n setTimeout(() => {\n this.syncMainContentAudioWhenVisible();\n }, 50);\n setTimeout(() => {\n this.syncMainContentAudioWhenVisible();\n }, 100);\n setTimeout(() => {\n this.syncMainContentAudioWhenVisible();\n }, 150);\n }\n if (isSmartTV && !restoredMuted) {\n [500, 1e3, 2e3, 3e3, 5e3].forEach((delay) => {\n setTimeout(() => {\n if (!this.inAdBreak && !this.adLayer.isAdPlaying()) {\n if (this.video.muted !== restoredMuted) this.video.muted = restoredMuted;\n if (Math.abs(this.video.volume - restoredVolume) > 0.01) this.video.volume = restoredVolume;\n }\n }, delay);\n });\n }\n this.savedMutedStateBeforeAd = null;\n }\n handleAdFailure() {\n this.consecutiveFailures++;\n if (this.config.debugAdTiming) {\n console.log(\n `[CONTINUOUS-FETCH] Ad failure: consecutiveFailures=${this.consecutiveFailures}`\n );\n }\n if (this.consecutiveFailures >= this.maxConsecutiveFailures) {\n if (this.config.debugAdTiming) {\n console.log(`[CONTINUOUS-FETCH] \\u{1F6D1} Max consecutive failures reached (${this.consecutiveFailures}), ending ad break gracefully`);\n }\n this.handleAdPodComplete();\n return;\n }\n if (this.inAdBreak && !this.config.disableFiller) {\n if (this.config.debugAdTiming) {\n console.log(\"[CONTINUOUS-FETCH] Ad failure in active break \\u2014 showing filler while awaiting next ad\");\n }\n this.showPlaceholderLayer();\n this.adLayer.showPlaceholder();\n } else if (this.inAdBreak) {\n if (this.config.debugAdTiming) {\n console.log(\"[CONTINUOUS-FETCH] Ad failure with no filler \\u2014 restoring main video temporarily\");\n }\n this.adLayer.hidePlaceholder();\n if (!this.adLayer.isAdPlaying() && this.video.paused && this.video.readyState >= 2) {\n this.video.play()?.catch(() => {\n });\n }\n }\n }\n startAdRequestWatchdog(token) {\n this.clearAdRequestWatchdog();\n const timeoutMs = this.config.adFailsafeTimeoutMs ?? 1e4;\n this.adRequestWatchdogToken = token;\n this.adRequestWatchdogId = window.setTimeout(() => {\n if (this.adRequestWatchdogToken !== token) {\n return;\n }\n this.adRequestWatchdogId = void 0;\n this.adRequestWatchdogToken = null;\n if (this.activeAdRequestToken === token) {\n this.activeAdRequestToken = null;\n }\n this.logAdState(\"ad_request_timeout\", { token, timeoutMs });\n this.handleAdFailure();\n }, timeoutMs);\n this.logAdState(\"ad_request_watchdog_started\", { token, timeoutMs });\n }\n clearAdRequestWatchdog() {\n if (this.adRequestWatchdogId != null) {\n clearTimeout(this.adRequestWatchdogId);\n this.adRequestWatchdogId = void 0;\n }\n if (this.adRequestWatchdogToken != null) {\n this.logAdState(\"ad_request_watchdog_cleared\", {\n token: this.adRequestWatchdogToken\n });\n this.adRequestWatchdogToken = null;\n }\n }\n startAdFailsafeTimer(token) {\n this.clearAdFailsafeTimer();\n const failsafeMs = this.config.adFailsafeTimeoutMs ?? 1e4;\n this.adFailsafeToken = token;\n this.adFailsafeTimerId = window.setTimeout(() => {\n if (this.adFailsafeToken !== token) {\n return;\n }\n this.adFailsafeTimerId = void 0;\n this.adFailsafeToken = null;\n if (this.activeAdRequestToken === token) {\n this.activeAdRequestToken = null;\n }\n this.logAdState(\"ad_failsafe_triggered\", {\n token,\n failsafeMs,\n videoPaused: this.video.paused,\n imaAdPlaying: this.adLayer.isAdPlaying()\n });\n this.handleAdFailure();\n }, failsafeMs);\n this.logAdState(\"ad_failsafe_started\", { token, failsafeMs });\n }\n clearAdFailsafeTimer() {\n if (this.adFailsafeTimerId != null) {\n clearTimeout(this.adFailsafeTimerId);\n this.logAdState(\"ad_failsafe_cleared\", { token: this.adFailsafeToken });\n this.adFailsafeTimerId = void 0;\n }\n this.adFailsafeToken = null;\n }\n logAdState(event, extra = {}) {\n if (!this.config.debugAdTiming) {\n return;\n }\n this.pushDebugLog(\"info\", \"ad-state\", event, extra);\n console.log(\"[StormcloudVideoPlayer][AdState]\", {\n event,\n timestamp: (/* @__PURE__ */ new Date()).toISOString(),\n showAds: this.showAds,\n adPlaying: this.adLayer.isAdPlaying(),\n inAdBreak: this.inAdBreak,\n activeAdRequestToken: this.activeAdRequestToken,\n ...extra\n });\n }\n getRemainingAdMs() {\n if (this.currentAdBreakStartWallClockMs == null) return 0;\n if (this.expectedAdBreakDurationMs == null) return Number.MAX_SAFE_INTEGER;\n const elapsed = Date.now() - this.currentAdBreakStartWallClockMs;\n return Math.max(0, this.expectedAdBreakDurationMs - elapsed);\n }\n pushDebugLog(level, category, message, details) {\n if (!this.config.debugAdTiming) return;\n this.debugLogEntries.push({\n timestampMs: Date.now(),\n level,\n category,\n message,\n ...details ? { details } : {}\n });\n if (this.debugLogEntries.length > DEBUG_HISTORY_LIMIT) {\n this.debugLogEntries = this.debugLogEntries.slice(-DEBUG_HISTORY_LIMIT);\n }\n }\n pushAdInsertionDebug(event, segmentName, opts) {\n if (!this.config.debugAdTiming) return;\n this.adInsertionDebugHistory.push({\n timestampMs: Date.now(),\n event,\n segmentName,\n ...opts?.offsetSeconds !== void 0 ? { offsetSeconds: opts.offsetSeconds } : {},\n ...opts?.updatedAt ? { updatedAt: opts.updatedAt } : {},\n ...opts?.detail ? { detail: opts.detail } : {}\n });\n if (this.adInsertionDebugHistory.length > DEBUG_HISTORY_LIMIT) {\n this.adInsertionDebugHistory = this.adInsertionDebugHistory.slice(-DEBUG_HISTORY_LIMIT);\n }\n }\n getAdInsertionDebugLog() {\n return this.adInsertionDebugHistory.slice();\n }\n getDebugLogs() {\n return this.debugLogEntries.slice();\n }\n toggleMute() {\n if (this.adLayer.isAdPlaying()) {\n const isAdCurrentlyMuted = this.adLayer.getAdVolume() === 0;\n if (isAdCurrentlyMuted) {\n const savedVolume = this.adLayer.getOriginalVolume() || 1;\n this.adLayer.setAdVolume(savedVolume);\n this.adLayer.updateOriginalMutedState(false, savedVolume);\n } else {\n const currentAdVolume = this.adLayer.getAdVolume();\n this.adLayer.setAdVolume(0);\n this.adLayer.updateOriginalMutedState(true, currentAdVolume);\n }\n if (this.config.debugAdTiming) {\n console.log(\n \"[StormcloudVideoPlayer] Mute toggle during ad:\",\n isAdCurrentlyMuted ? \"unmuted\" : \"muted\"\n );\n }\n } else {\n this.video.muted = !this.video.muted;\n this.adLayer.updateOriginalMutedState(this.video.muted, this.video.volume);\n if (this.config.debugAdTiming) {\n console.log(\"[StormcloudVideoPlayer] Muted:\", this.video.muted);\n }\n }\n }\n toggleFullscreen() {\n return new Promise((resolve, reject) => {\n if (!document.fullscreenElement) {\n const container = this.video.parentElement;\n if (!container) {\n reject(new Error(\"No parent container found for fullscreen\"));\n return;\n }\n container.requestFullscreen().then(() => {\n if (this.config.debugAdTiming) {\n console.log(\"[StormcloudVideoPlayer] Entered fullscreen\");\n }\n resolve();\n }).catch((err) => {\n if (this.config.debugAdTiming) {\n console.error(\"[StormcloudVideoPlayer] Fullscreen error:\", err);\n }\n reject(err);\n });\n } else {\n document.exitFullscreen().then(() => {\n if (this.config.debugAdTiming) {\n console.log(\"[StormcloudVideoPlayer] Exited fullscreen\");\n }\n resolve();\n }).catch((err) => {\n if (this.config.debugAdTiming) {\n console.error(\n \"[StormcloudVideoPlayer] Exit fullscreen error:\",\n err\n );\n }\n reject(err);\n });\n }\n });\n }\n isMuted() {\n if (this.adLayer.isAdPlaying()) {\n const adMuted = this.adLayer.getAdVolume() === 0;\n if (this.config.debugAdTiming) {\n console.log(\n \"[StormcloudVideoPlayer] isMuted() during ad playback ->\",\n adMuted\n );\n }\n return adMuted;\n }\n return this.video.muted;\n }\n setMuted(muted) {\n const adPlaying = this.adLayer.isAdPlaying();\n if (adPlaying) {\n const savedVolume = this.adLayer.getOriginalVolume() || 1;\n this.adLayer.setAdVolume(muted ? 0 : savedVolume);\n this.adLayer.updateOriginalMutedState(muted, savedVolume);\n if (this.config.debugAdTiming) {\n console.log(\"[StormcloudVideoPlayer] setMuted applied to ad layer (content stays muted)\", {\n muted,\n savedVolume\n });\n }\n return;\n }\n this.video.muted = muted;\n if (!this.inAdBreak) {\n this.adLayer.updateOriginalMutedState(muted, this.video.volume);\n }\n if (this.config.debugAdTiming) {\n console.log(\"[StormcloudVideoPlayer] setMuted called:\", muted);\n }\n }\n setVolume(volume) {\n const clampedVolume = Math.max(0, Math.min(1, volume));\n const adPlaying = this.adLayer.isAdPlaying();\n if (adPlaying) {\n this.adLayer.setAdVolume(clampedVolume);\n const preservedVolume = clampedVolume > 0 ? clampedVolume : this.adLayer.getOriginalVolume();\n this.adLayer.updateOriginalMutedState(clampedVolume === 0, preservedVolume);\n if (this.config.debugAdTiming) {\n console.log(\"[StormcloudVideoPlayer] setVolume applied during ad\", {\n volume: clampedVolume\n });\n }\n } else {\n this.video.volume = clampedVolume;\n this.video.muted = clampedVolume === 0;\n if (!this.inAdBreak) {\n this.adLayer.updateOriginalMutedState(clampedVolume === 0, clampedVolume);\n }\n if (this.config.debugAdTiming) {\n console.log(\"[StormcloudVideoPlayer] setVolume called:\", clampedVolume);\n }\n }\n }\n getVolume() {\n const adPlaying = this.adLayer.isAdPlaying();\n if (adPlaying) {\n return this.adLayer.getAdVolume();\n }\n return this.video.volume;\n }\n isFullscreen() {\n return !!document.fullscreenElement;\n }\n isLive() {\n return this.isLiveStream;\n }\n getMinHlsResolution() {\n const levels = this.hls?.levels;\n if (!levels || levels.length === 0) return null;\n let min = null;\n let minPixels = Infinity;\n for (const level of levels) {\n if (level.width && level.height) {\n const pixels = level.width * level.height;\n if (pixels < minPixels) {\n minPixels = pixels;\n min = { width: level.width, height: level.height };\n }\n }\n }\n return min;\n }\n getMaxHlsResolution() {\n const levels = this.hls?.levels;\n if (!levels || levels.length === 0) return null;\n let max = null;\n let maxPixels = 0;\n for (const level of levels) {\n if (level.width && level.height) {\n const pixels = level.width * level.height;\n if (pixels > maxPixels) {\n maxPixels = pixels;\n max = { width: level.width, height: level.height };\n }\n }\n }\n return max;\n }\n getCurrentHlsSegmentDurationMs() {\n const fallbackMs = 4e3;\n if (this.nativeHlsMode) {\n return fallbackMs;\n }\n const hls = this.hls;\n if (!hls) return null;\n const levelCandidates = [hls.currentLevel, hls.nextLoadLevel, hls.loadLevel];\n for (const levelIndex of levelCandidates) {\n if (typeof levelIndex !== \"number\" || levelIndex < 0) continue;\n const details = hls.levels?.[levelIndex]?.details;\n if (!details) continue;\n const targetDurationSec = typeof details.partTarget === \"number\" && details.partTarget > 0 ? details.partTarget : typeof details.targetduration === \"number\" && details.targetduration > 0 ? details.targetduration : void 0;\n if (targetDurationSec !== void 0) {\n return Math.max(800, Math.floor(targetDurationSec * 1e3));\n }\n }\n return fallbackMs;\n }\n get videoElement() {\n return this.video;\n }\n resize() {\n if (this.config.debugAdTiming) {\n console.log(\"[StormcloudVideoPlayer] Resizing player\");\n }\n if (this.adLayer && this.adLayer.isAdPlaying()) {\n const width = this.video.clientWidth || 640;\n const height = this.video.clientHeight || 480;\n if (this.config.debugAdTiming) {\n console.log(\n `[StormcloudVideoPlayer] Resizing ads manager to ${width}x${height}`\n );\n }\n this.adLayer.resize(width, height);\n }\n }\n destroy() {\n this.stopAdInsertionPolling();\n this.clearAdInsertionOffsetTimer();\n this.stopContinuousFetching();\n this.stopFillerBreakTimer();\n this.clearAdStopTimer();\n this.clearAdFailsafeTimer();\n this.clearAdRequestWatchdog();\n this.clearPendingAdBreak();\n if (this.fillerVideo) {\n this.fillerVideo.pause();\n if (this.fillerVideo.parentElement) {\n this.fillerVideo.parentElement.removeChild(this.fillerVideo);\n }\n this.fillerVideo = void 0;\n }\n if (this.timeUpdateHandler) {\n this.video.removeEventListener(\"timeupdate\", this.timeUpdateHandler);\n delete this.timeUpdateHandler;\n }\n if (this.emptiedHandler) {\n this.video.removeEventListener(\"emptied\", this.emptiedHandler);\n delete this.emptiedHandler;\n }\n if (this.heartbeatInterval) {\n clearInterval(this.heartbeatInterval);\n this.heartbeatInterval = void 0;\n }\n this.hls?.destroy();\n this.adLayer?.destroy();\n this.consecutiveFailures = 0;\n this.debugLogEntries = [];\n this.adInsertionDebugHistory = [];\n }\n};\n\n// src/ui/StormcloudVideoPlayer.tsx\nvar import_fa = require(\"react-icons/fa\");\n\n// src/ui/OverlayRenderer.tsx\nvar import_react = __toESM(require(\"react\"), 1);\n\n// src/utils/overlays.ts\nvar OVERLAY_API_BASE = \"https://adstorm.co/api-adstorm-dev\";\nfunction timeStringToSeconds(timeStr) {\n if (!timeStr) return 0;\n const parts = timeStr.split(\":\");\n if (parts.length >= 3) {\n const hours = parseInt(parts[0] ?? \"0\", 10) || 0;\n const minutes = parseInt(parts[1] ?? \"0\", 10) || 0;\n const secStr = parts[2] ?? \"0\";\n const dotIdx = secStr.indexOf(\".\");\n const seconds = parseInt(dotIdx >= 0 ? secStr.substring(0, dotIdx) : secStr, 10) || 0;\n const msFrag = dotIdx >= 0 ? secStr.substring(dotIdx + 1) : \"\";\n const ms = msFrag ? parseInt(msFrag.padEnd(3, \"0\").substring(0, 3), 10) || 0 : 0;\n return hours * 3600 + minutes * 60 + seconds + ms / 1e3;\n }\n if (parts.length === 2) {\n const minutes = parseInt(parts[0] ?? \"0\", 10) || 0;\n const secStr = parts[1] ?? \"0\";\n const dotIdx = secStr.indexOf(\".\");\n const seconds = parseInt(dotIdx >= 0 ? secStr.substring(0, dotIdx) : secStr, 10) || 0;\n const msFrag = dotIdx >= 0 ? secStr.substring(dotIdx + 1) : \"\";\n const ms = msFrag ? parseInt(msFrag.padEnd(3, \"0\").substring(0, 3), 10) || 0 : 0;\n return minutes * 60 + seconds + ms / 1e3;\n }\n const num = parseFloat(timeStr);\n return isFinite(num) ? Math.max(0, num) : 0;\n}\nfunction isOverlayActive(overlay, currentTime) {\n if (!overlay.visible) return false;\n const startSec = timeStringToSeconds(overlay.start_time);\n const durationSec = timeStringToSeconds(overlay.duration);\n if (durationSec <= 0) return false;\n return currentTime >= startSec && currentTime < startSec + durationSec;\n}\nfunction normalizeScrollerConfig(raw) {\n if (!raw || typeof raw !== \"object\") return void 0;\n const r = raw;\n const merged = { ...raw };\n if (merged.use_custom_text === void 0 && typeof r.useCustomText === \"boolean\") {\n merged.use_custom_text = r.useCustomText;\n }\n if ((merged.custom_text === void 0 || merged.custom_text === \"\") && typeof r.customText === \"string\") {\n merged.custom_text = r.customText;\n }\n if (!merged.rss_url && typeof r.rssUrl === \"string\") {\n merged.rss_url = r.rssUrl;\n }\n return merged;\n}\nfunction normalizeSwirlOverlay(raw) {\n const o = { ...raw };\n if (o.type === \"scroller\") {\n const sc = raw.scroller_config ?? raw.scrollerConfig;\n const normalized = normalizeScrollerConfig(sc);\n if (normalized) o.scroller_config = normalized;\n }\n return o;\n}\nasync function fetchProjectOverlays(projectId, apiBaseUrl = OVERLAY_API_BASE) {\n const base = apiBaseUrl.replace(/\\/$/, \"\");\n const response = await fetch(\n `${base}/adstorm/swirl/projects/${projectId}/overlays`\n );\n if (!response.ok) {\n throw new Error(\n `Failed to fetch overlays: ${response.status} ${response.statusText}`\n );\n }\n const data = await response.json();\n if (!Array.isArray(data)) return [];\n return data.map(\n (row) => normalizeSwirlOverlay(row)\n );\n}\nfunction resolveImageUrl(imageUrl, apiBaseUrl = OVERLAY_API_BASE) {\n if (!imageUrl) return \"\";\n if (imageUrl.startsWith(\"http://\") || imageUrl.startsWith(\"https://\")) {\n return imageUrl;\n }\n if (imageUrl.startsWith(\"/\")) {\n try {\n const url = new URL(apiBaseUrl);\n return `${url.origin}${imageUrl}`;\n } catch {\n return imageUrl;\n }\n }\n return `${apiBaseUrl}/${imageUrl}`;\n}\n\n// src/ui/OverlayRenderer.tsx\nvar import_jsx_runtime = require(\"react/jsx-runtime\");\nfunction computeVideoDimensions(video) {\n const nativeWidth = video.videoWidth;\n const nativeHeight = video.videoHeight;\n if (!nativeWidth || !nativeHeight) return null;\n const displayWidth = video.offsetWidth;\n const displayHeight = video.offsetHeight;\n if (!displayWidth || !displayHeight) return null;\n const videoAspect = nativeWidth / nativeHeight;\n const displayAspect = displayWidth / displayHeight;\n let renderWidth;\n let renderHeight;\n let offsetX;\n let offsetY;\n if (videoAspect > displayAspect) {\n renderWidth = displayWidth;\n renderHeight = displayWidth / videoAspect;\n offsetX = 0;\n offsetY = (displayHeight - renderHeight) / 2;\n } else {\n renderHeight = displayHeight;\n renderWidth = displayHeight * videoAspect;\n offsetX = (displayWidth - renderWidth) / 2;\n offsetY = 0;\n }\n return {\n nativeWidth,\n nativeHeight,\n displayWidth: renderWidth,\n displayHeight: renderHeight,\n offsetX,\n offsetY,\n scaleX: renderWidth / nativeWidth,\n scaleY: renderHeight / nativeHeight\n };\n}\nfunction ImageOverlay({ overlay }) {\n const src = resolveImageUrl(overlay.image_url || \"\");\n if (!src) return null;\n return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(\n \"img\",\n {\n src,\n alt: overlay.name,\n draggable: false,\n style: {\n width: \"100%\",\n height: \"100%\",\n objectFit: \"contain\",\n display: \"block\",\n pointerEvents: \"none\",\n userSelect: \"none\"\n }\n }\n );\n}\nfunction TextOverlay({ overlay }) {\n const text = overlay.content || \"\";\n return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(\n \"div\",\n {\n style: {\n width: \"100%\",\n height: \"100%\",\n display: \"flex\",\n alignItems: \"center\",\n justifyContent: \"center\",\n color: \"#ffffff\",\n fontSize: \"clamp(10px, 1.4vw, 20px)\",\n fontFamily: \"Roboto, 'Segoe UI', Arial, sans-serif\",\n fontWeight: 600,\n textAlign: \"center\",\n padding: \"4px 8px\",\n boxSizing: \"border-box\",\n wordBreak: \"break-word\",\n textShadow: \"0 1px 4px rgba(0,0,0,0.7)\",\n pointerEvents: \"none\",\n userSelect: \"none\",\n lineHeight: 1.3\n },\n children: text\n }\n );\n}\nfunction parseRSSXml(xmlText, maxItems) {\n const stripped = xmlText.replace(/^<\\?xml[^?]*\\?>\\s*/, \"\");\n const parser = new DOMParser();\n const doc = parser.parseFromString(stripped, \"text/xml\");\n const items = Array.from(doc.querySelectorAll(\"item\")).map((item) => ({\n title: (item.querySelector(\"title\")?.textContent || \"\").replace(/<[^>]*>/g, \"\").trim(),\n description: (item.querySelector(\"description\")?.textContent || \"\").replace(/<[^>]*>/g, \"\").trim(),\n pubDate: item.querySelector(\"pubDate\")?.textContent || \"\",\n author: item.querySelector(\"author, dc\\\\:creator\")?.textContent || \"\",\n category: item.querySelector(\"category\")?.textContent || \"\"\n })).filter((i) => i.title).slice(0, maxItems);\n if (items.length === 0 && doc.querySelector(\"parsererror\")) {\n throw new Error(\"Invalid RSS XML\");\n }\n return items;\n}\nvar RSS_CACHE_TTL_MS = 6e4;\nvar rssCache = /* @__PURE__ */ new Map();\nfunction cachedFetchRSSItems(rssUrl, maxItems) {\n const now = Date.now();\n const cached = rssCache.get(rssUrl);\n if (cached && cached.expiresAt > now) return cached.promise;\n const promise = fetchRSSItems(rssUrl, maxItems).catch((err) => {\n rssCache.delete(rssUrl);\n throw err;\n });\n rssCache.set(rssUrl, { promise, expiresAt: now + RSS_CACHE_TTL_MS });\n return promise;\n}\nasync function fetchRSSItems(rssUrl, maxItems) {\n const encoded = encodeURIComponent(rssUrl);\n try {\n const origin = typeof window !== \"undefined\" ? window.location.origin : \"\";\n const resp = await fetch(`${origin}/api/rss-proxy?url=${encoded}`);\n if (resp.ok) {\n const text = await resp.text();\n if (text.includes(\"<item\")) return parseRSSXml(text, maxItems);\n }\n } catch {\n }\n try {\n const resp = await fetch(`https://api.allorigins.win/get?url=${encoded}`);\n if (resp.ok) {\n const data = await resp.json();\n if (data.contents) return parseRSSXml(data.contents, maxItems);\n }\n } catch {\n }\n try {\n const resp = await fetch(`https://corsproxy.io/?url=${encoded}`);\n if (resp.ok) {\n const text = await resp.text();\n if (text) return parseRSSXml(text, maxItems);\n }\n } catch {\n }\n throw new Error(\"All RSS proxies failed\");\n}\nfunction ScrollerOverlay({ overlay }) {\n const cfg = overlay.scroller_config;\n const uid = (0, import_react.useId)().replace(/:/g, \"\");\n const [rssItems, setRssItems] = (0, import_react.useState)([]);\n const [rssLoading, setRssLoading] = (0, import_react.useState)(true);\n const [rssError, setRssError] = (0, import_react.useState)(false);\n const rssUrl = cfg?.rss_url || \"\";\n const maxItems = cfg?.max_items ?? 10;\n const autoRefresh = cfg?.auto_refresh !== false;\n const updateInterval = cfg?.update_interval ?? 5;\n (0, import_react.useEffect)(() => {\n if (!rssUrl || cfg?.use_custom_text && cfg?.custom_text) {\n setRssLoading(false);\n return;\n }\n let cancelled = false;\n setRssLoading(true);\n setRssError(false);\n cachedFetchRSSItems(rssUrl, maxItems).then((items) => {\n if (!cancelled) {\n setRssItems(items);\n setRssError(false);\n }\n }).catch(() => {\n if (!cancelled) setRssError(true);\n }).finally(() => {\n if (!cancelled) setRssLoading(false);\n });\n return () => {\n cancelled = true;\n };\n }, [rssUrl, maxItems, cfg?.use_custom_text, cfg?.custom_text]);\n (0, import_react.useEffect)(() => {\n if (!rssUrl || !autoRefresh || cfg?.use_custom_text && cfg?.custom_text) return;\n const interval = setInterval(() => {\n rssCache.delete(rssUrl);\n cachedFetchRSSItems(rssUrl, maxItems).then((items) => {\n setRssItems(items);\n setRssError(false);\n }).catch(() => {\n });\n }, updateInterval * 60 * 1e3);\n return () => clearInterval(interval);\n }, [rssUrl, autoRefresh, updateInterval, maxItems, cfg?.use_custom_text, cfg?.custom_text]);\n const sep = cfg?.separator_char ?? \"\\u25C6\";\n let segments;\n if (cfg?.use_custom_text && cfg?.custom_text) {\n segments = [cfg.custom_text];\n } else if (rssItems.length > 0) {\n segments = rssItems.map((item) => {\n const parts = [];\n if (cfg?.show_title !== false && item.title) parts.push(item.title);\n if (cfg?.show_description && item.description) parts.push(item.description);\n if (cfg?.show_timestamp && item.pubDate) {\n try {\n parts.push(new Date(item.pubDate).toLocaleDateString());\n } catch {\n }\n }\n if (cfg?.show_author && item.author) parts.push(`\\u2014 ${item.author}`);\n if (cfg?.show_category && item.category) parts.push(`[${item.category}]`);\n return parts.join(\" \");\n });\n } else if (rssLoading) {\n segments = [\"Loading feed\\u2026\"];\n } else if (rssError) {\n segments = overlay.content ? [overlay.content] : [\"RSS feed unavailable\"];\n } else if (overlay.content) {\n segments = [overlay.content];\n } else {\n segments = rssUrl ? [\"Loading feed\\u2026\"] : [\"RSS Ticker\"];\n }\n const scrollSpeed = cfg?.scroll_speed ?? 40;\n const direction = cfg?.direction ?? \"left\";\n const fontSize = cfg?.font_size ?? 15;\n const fontFamily = cfg?.font_family || \"Roboto, 'Segoe UI', Arial, sans-serif\";\n const fontWeight = cfg?.font_weight || \"700\";\n const textColor = cfg?.text_color || \"#ffffff\";\n const bgColor = cfg?.background_color || \"#0d0d1a\";\n const bgOpacity = cfg?.background_opacity !== void 0 ? cfg.background_opacity / 100 : 0.95;\n const borderRadius = cfg?.border_radius ?? 0;\n const itemSpacing = cfg?.item_spacing ?? 60;\n const pad = cfg?.padding !== void 0 && cfg.padding >= 0 ? cfg.padding : 8;\n const label = cfg?.label ?? \"NEWS\";\n const labelLine2 = cfg?.label_line2 ?? \"\";\n const labelColor = cfg?.label_color ?? \"#f97316\";\n const labelTextColor = cfg?.label_text_color ?? \"#ffffff\";\n const accentColor = cfg?.accent_color ?? labelColor;\n const showAccentLine = cfg?.show_accent_line !== false;\n const isEquitiesStrip = cfg?.preset === \"equities_strip\";\n const isHorizontal = direction === \"left\" || direction === \"right\";\n const isReverse = direction === \"right\" || direction === \"down\";\n const fullText = segments.join(` ${sep} `);\n const durationSec = Math.max(6, fullText.length * 9 / scrollSpeed);\n const animId = `sc-ticker-${overlay.id}-${uid}`;\n const keyframes = isHorizontal ? `@keyframes ${animId} {\n ${isReverse ? \"0% { transform: translateX(-50%); } 100% { transform: translateX(0%); }\" : \"0% { transform: translateX(0); } 100% { transform: translateX(-50%); }\"}\n }` : `@keyframes ${animId} {\n ${isReverse ? \"0% { transform: translateY(-50%); } 100% { transform: translateY(0%); }\" : \"0% { transform: translateY(0); } 100% { transform: translateY(-50%); }\"}\n }`;\n return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(import_jsx_runtime.Fragment, { children: [\n /* @__PURE__ */ (0, import_jsx_runtime.jsx)(\"style\", { children: keyframes }),\n /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(\n \"div\",\n {\n style: {\n width: \"100%\",\n height: \"100%\",\n display: \"flex\",\n flexDirection: \"column\",\n overflow: \"hidden\",\n borderRadius: borderRadius > 0 ? `${borderRadius}px` : void 0,\n backgroundColor: `rgba(${hexToRgb(bgColor)}, ${bgOpacity})`,\n fontFamily,\n fontSize: `${fontSize}px`,\n fontWeight,\n color: textColor,\n pointerEvents: \"none\",\n userSelect: \"none\"\n },\n children: [\n showAccentLine && /* @__PURE__ */ (0, import_jsx_runtime.jsx)(\n \"div\",\n {\n style: {\n height: isEquitiesStrip ? 2 : 3,\n background: accentColor,\n flexShrink: 0,\n width: \"100%\"\n }\n }\n ),\n /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(\n \"div\",\n {\n style: {\n display: \"flex\",\n flex: 1,\n overflow: \"hidden\",\n minHeight: 0,\n alignItems: \"center\",\n padding: isEquitiesStrip ? `${Math.max(2, pad * 0.5)}px ${pad}px` : `${Math.max(4, pad * 0.75)}px ${pad}px`,\n gap: isEquitiesStrip ? Math.max(4, Math.round(pad * 0.75)) : Math.max(6, pad),\n boxSizing: \"border-box\"\n },\n children: [\n label && /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(\n \"div\",\n {\n style: {\n background: labelColor,\n color: labelTextColor,\n padding: isEquitiesStrip ? \"6px 12px\" : \"10px 14px\",\n display: \"flex\",\n flexDirection: isEquitiesStrip ? \"row\" : \"column\",\n alignItems: \"center\",\n justifyContent: \"center\",\n flexShrink: 0,\n textAlign: \"center\",\n gap: isEquitiesStrip ? 0 : 2,\n borderRadius: Math.max(2, borderRadius > 0 ? borderRadius : 6),\n boxShadow: isEquitiesStrip ? \"inset 0 1px 0 rgba(255,255,255,0.08)\" : \"0 2px 8px rgba(0,0,0,0.35)\",\n alignSelf: \"stretch\",\n maxWidth: isEquitiesStrip ? \"min(200px, 28%)\" : void 0\n },\n children: [\n /* @__PURE__ */ (0, import_jsx_runtime.jsx)(\n \"span\",\n {\n style: {\n fontWeight: isEquitiesStrip ? 700 : 800,\n fontSize: isEquitiesStrip ? \"0.82em\" : \"0.78em\",\n letterSpacing: isEquitiesStrip ? \"0.04em\" : \"0.08em\",\n lineHeight: 1.2,\n textTransform: isEquitiesStrip ? \"none\" : \"uppercase\",\n whiteSpace: isEquitiesStrip ? \"normal\" : \"nowrap\",\n textAlign: isEquitiesStrip ? \"left\" : \"center\"\n },\n children: label\n }\n ),\n labelLine2 && !isEquitiesStrip && /* @__PURE__ */ (0, import_jsx_runtime.jsx)(\n \"span\",\n {\n style: {\n fontWeight: 600,\n fontSize: \"0.58em\",\n letterSpacing: \"0.06em\",\n lineHeight: 1.15,\n opacity: 0.92,\n whiteSpace: \"nowrap\"\n },\n children: labelLine2\n }\n )\n ]\n }\n ),\n label && /* @__PURE__ */ (0, import_jsx_runtime.jsx)(\n \"div\",\n {\n style: {\n width: isEquitiesStrip ? 1 : 2,\n alignSelf: \"stretch\",\n minHeight: isEquitiesStrip ? 20 : 24,\n background: accentColor,\n flexShrink: 0,\n borderRadius: 1,\n opacity: 0.85\n }\n }\n ),\n /* @__PURE__ */ (0, import_jsx_runtime.jsx)(\n \"div\",\n {\n style: {\n flex: 1,\n overflow: \"hidden\",\n position: \"relative\",\n display: \"flex\",\n alignItems: \"center\",\n minWidth: 0\n },\n children: isHorizontal ? /* @__PURE__ */ (0, import_jsx_runtime.jsx)(\n \"div\",\n {\n style: {\n display: \"inline-flex\",\n whiteSpace: \"nowrap\",\n animation: `${animId} ${durationSec}s linear infinite`,\n willChange: \"transform\"\n },\n children: [0, 1].map((copy) => /* @__PURE__ */ (0, import_jsx_runtime.jsx)(\"span\", { style: { paddingRight: `${itemSpacing}px` }, children: segments.map((seg, i) => /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(import_react.default.Fragment, { children: [\n i > 0 && /* @__PURE__ */ (0, import_jsx_runtime.jsx)(\"span\", { style: { opacity: 0.5, margin: \"0 8px\" }, children: sep }),\n /* @__PURE__ */ (0, import_jsx_runtime.jsx)(\"span\", { style: { textShadow: \"0 1px 3px rgba(0,0,0,0.6)\" }, children: seg })\n ] }, i)) }, copy))\n }\n ) : /* @__PURE__ */ (0, import_jsx_runtime.jsx)(\n \"div\",\n {\n style: {\n display: \"flex\",\n flexDirection: \"column\",\n whiteSpace: \"nowrap\",\n animation: `${animId} ${durationSec}s linear infinite`,\n willChange: \"transform\"\n },\n children: [0, 1].map(\n (copy) => segments.map((seg, i) => /* @__PURE__ */ (0, import_jsx_runtime.jsx)(\"div\", { style: { paddingBottom: `${itemSpacing / 4}px` }, children: seg }, `${copy}-${i}`))\n )\n }\n )\n }\n )\n ]\n }\n )\n ]\n }\n )\n ] });\n}\nfunction parseConfig(content) {\n if (!content) return null;\n try {\n return JSON.parse(content);\n } catch {\n return null;\n }\n}\nfunction parseClockMMSS(clock) {\n if (!clock) return null;\n const m = /^\\s*(\\d{1,3}):([0-5]?\\d)\\s*$/.exec(clock);\n if (!m) return null;\n return parseInt(m[1], 10) * 60 + parseInt(m[2], 10);\n}\nfunction formatClockMMSS(totalSec) {\n const s = Math.max(0, Math.floor(totalSec));\n const mm = Math.floor(s / 60);\n const ss = s % 60;\n return `${mm}:${ss.toString().padStart(2, \"0\")}`;\n}\nfunction useScoreBugClock(overlayId, sourceClock) {\n const initialSec = parseClockMMSS(sourceClock);\n const [now, setNow] = (0, import_react.useState)(() => Date.now());\n const startRef = (0, import_react.useRef)(null);\n (0, import_react.useEffect)(() => {\n if (initialSec === null) {\n startRef.current = null;\n return;\n }\n startRef.current = {\n id: overlayId,\n source: sourceClock || \"\",\n at: Date.now(),\n seconds: initialSec\n };\n setNow(Date.now());\n const tick = window.setInterval(() => setNow(Date.now()), 500);\n return () => clearInterval(tick);\n }, [overlayId, sourceClock, initialSec]);\n if (initialSec === null || !startRef.current) return null;\n const elapsed = Math.floor((now - startRef.current.at) / 1e3);\n const remaining = Math.max(0, startRef.current.seconds - elapsed);\n return formatClockMMSS(remaining);\n}\nfunction ScoreBugOverlay({ overlay, size }) {\n const cfg = parseConfig(overlay.content);\n const liveClock = useScoreBugClock(overlay.id, cfg?.clock);\n if (!cfg) return null;\n const f = Math.max(6, size.w * 0.052);\n const displayClock = liveClock ?? cfg.clock ?? \"\";\n const displayPeriod = cfg.period ?? \"\";\n const showMiddleCol = Boolean(displayPeriod || displayClock);\n return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(\n \"div\",\n {\n style: {\n width: \"100%\",\n height: \"100%\",\n borderRadius: Math.max(2, size.w * 0.028),\n display: \"flex\",\n flexDirection: \"column\",\n background: cfg.backgroundColor,\n color: cfg.textColor,\n fontFamily: \"'Inter', 'Roboto', 'Segoe UI', system-ui, sans-serif\",\n overflow: \"hidden\",\n pointerEvents: \"none\",\n userSelect: \"none\",\n fontSize: `${f}px`,\n boxShadow: \"0 8px 28px rgba(0,0,0,0.45)\"\n },\n children: [\n /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(\n \"div\",\n {\n style: {\n flex: 1,\n display: \"flex\",\n alignItems: \"center\",\n padding: `${f * 0.42}px ${f * 0.85}px`,\n gap: f * 0.45,\n minHeight: 0\n },\n children: [\n /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(\"div\", { style: { flex: 1, textAlign: \"center\", minWidth: 0, padding: `0 ${f * 0.15}px` }, children: [\n /* @__PURE__ */ (0, import_jsx_runtime.jsx)(\n \"div\",\n {\n style: {\n fontSize: \"1.05em\",\n fontWeight: 800,\n letterSpacing: \"0.02em\",\n overflow: \"hidden\",\n textOverflow: \"ellipsis\",\n whiteSpace: \"nowrap\"\n },\n children: cfg.homeTeam\n }\n ),\n /* @__PURE__ */ (0, import_jsx_runtime.jsx)(\"div\", { style: { fontSize: \"1.75em\", fontWeight: 900, lineHeight: 1.05, marginTop: f * 0.08 }, children: cfg.homeScore })\n ] }),\n showMiddleCol && /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(\n \"div\",\n {\n style: {\n fontSize: \"0.88em\",\n textAlign: \"center\",\n fontWeight: 600,\n opacity: 0.92,\n color: cfg.textColor,\n padding: `0 ${f * 0.5}px`,\n flexShrink: 0,\n lineHeight: 1.25,\n textTransform: \"uppercase\",\n letterSpacing: \"0.04em\"\n },\n children: [\n displayPeriod && /* @__PURE__ */ (0, import_jsx_runtime.jsx)(\"div\", { children: displayPeriod }),\n displayClock && /* @__PURE__ */ (0, import_jsx_runtime.jsx)(\"div\", { style: { fontWeight: 700, opacity: 1 }, children: displayClock })\n ]\n }\n ),\n /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(\"div\", { style: { flex: 1, textAlign: \"center\", minWidth: 0, padding: `0 ${f * 0.15}px` }, children: [\n /* @__PURE__ */ (0, import_jsx_runtime.jsx)(\n \"div\",\n {\n style: {\n fontSize: \"1.05em\",\n fontWeight: 800,\n letterSpacing: \"0.02em\",\n overflow: \"hidden\",\n textOverflow: \"ellipsis\",\n whiteSpace: \"nowrap\"\n },\n children: cfg.awayTeam\n }\n ),\n /* @__PURE__ */ (0, import_jsx_runtime.jsx)(\"div\", { style: { fontSize: \"1.75em\", fontWeight: 900, lineHeight: 1.05, marginTop: f * 0.08 }, children: cfg.awayScore })\n ] })\n ]\n }\n ),\n (cfg.sponsorText || cfg.sponsorImageUrl) && /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(\n \"div\",\n {\n style: {\n fontSize: \"0.72em\",\n textAlign: \"center\",\n fontWeight: 600,\n opacity: 0.88,\n padding: `${f * 0.34}px ${f * 0.55}px`,\n borderTop: `1px solid ${cfg.accentColor}55`,\n display: \"flex\",\n alignItems: \"center\",\n justifyContent: \"center\",\n gap: f * 0.45,\n overflow: \"hidden\",\n letterSpacing: \"0.04em\",\n textTransform: \"uppercase\",\n background: `linear-gradient(180deg, rgba(0,0,0,0.12) 0%, rgba(0,0,0,0.22) 100%)`\n },\n children: [\n cfg.sponsorImageUrl && /* @__PURE__ */ (0, import_jsx_runtime.jsx)(\"img\", { src: cfg.sponsorImageUrl, alt: \"sponsor\", style: { height: `${f * 1.35}px`, objectFit: \"contain\", flexShrink: 0 } }),\n cfg.sponsorText && /* @__PURE__ */ (0, import_jsx_runtime.jsx)(\"span\", { style: { overflow: \"hidden\", textOverflow: \"ellipsis\", whiteSpace: \"nowrap\" }, children: cfg.sponsorText })\n ]\n }\n )\n ]\n }\n );\n}\nfunction LowerThirdOverlay({ overlay, size }) {\n const cfg = parseConfig(overlay.content);\n if (!cfg) return null;\n const f = Math.max(6, size.w * 0.05);\n const accentH = Math.max(3, size.h * 0.038);\n return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(\n \"div\",\n {\n style: {\n width: \"100%\",\n height: \"100%\",\n borderRadius: Math.max(2, size.w * 0.018),\n display: \"flex\",\n flexDirection: \"column\",\n justifyContent: \"flex-end\",\n background: cfg.backgroundColor,\n color: cfg.textColor,\n fontFamily: \"'Inter', 'Roboto', 'Segoe UI', system-ui, sans-serif\",\n overflow: \"hidden\",\n pointerEvents: \"none\",\n userSelect: \"none\",\n fontSize: `${f}px`,\n boxShadow: \"0 10px 32px rgba(0,0,0,0.4)\"\n },\n children: [\n /* @__PURE__ */ (0, import_jsx_runtime.jsx)(\"div\", { style: { width: \"100%\", height: accentH, backgroundColor: cfg.accentColor, flexShrink: 0 } }),\n /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(\n \"div\",\n {\n style: {\n flex: 1,\n display: \"flex\",\n flexDirection: \"column\",\n justifyContent: \"center\",\n padding: `${f * 0.62}px ${f * 1.05}px`,\n minHeight: 0,\n gap: f * 0.18\n },\n children: [\n /* @__PURE__ */ (0, import_jsx_runtime.jsx)(\n \"div\",\n {\n style: {\n fontSize: \"1.28em\",\n fontWeight: 800,\n lineHeight: 1.22,\n letterSpacing: \"0.01em\",\n textShadow: \"0 2px 6px rgba(0,0,0,0.55)\"\n },\n children: cfg.headline\n }\n ),\n /* @__PURE__ */ (0, import_jsx_runtime.jsx)(\n \"div\",\n {\n style: {\n fontSize: \"0.94em\",\n fontWeight: 500,\n opacity: 0.92,\n lineHeight: 1.35,\n color: cfg.textColor\n },\n children: cfg.subtitle\n }\n )\n ]\n }\n ),\n (cfg.sponsorText || cfg.sponsorImageUrl) && /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(\n \"div\",\n {\n style: {\n fontSize: \"0.68em\",\n fontWeight: 600,\n opacity: 0.72,\n padding: `${f * 0.28}px ${f * 1.05}px ${f * 0.48}px`,\n display: \"flex\",\n alignItems: \"center\",\n gap: f * 0.4,\n overflow: \"hidden\",\n letterSpacing: \"0.06em\",\n textTransform: \"uppercase\",\n borderTop: `1px solid rgba(255,255,255,0.08)`\n },\n children: [\n cfg.sponsorImageUrl && /* @__PURE__ */ (0, import_jsx_runtime.jsx)(\"img\", { src: cfg.sponsorImageUrl, alt: \"sponsor\", style: { height: `${f * 1.25}px`, objectFit: \"contain\", flexShrink: 0 } }),\n cfg.sponsorText && /* @__PURE__ */ (0, import_jsx_runtime.jsx)(\"span\", { style: { overflow: \"hidden\", textOverflow: \"ellipsis\", whiteSpace: \"nowrap\" }, children: cfg.sponsorText })\n ]\n }\n )\n ]\n }\n );\n}\nfunction QrCodeOverlay({ overlay, size }) {\n const cfg = parseConfig(overlay.content);\n if (!cfg) return null;\n const qrSide = Math.max(32, Math.min(size.w, size.h) * 0.55);\n const qrUrl = `https://api.qrserver.com/v1/create-qr-code/?size=${Math.round(qrSide * 2)}x${Math.round(qrSide * 2)}&data=${encodeURIComponent(cfg.url || \"https://example.com\")}`;\n const f = Math.max(6, size.w * 0.06);\n return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(\"div\", { style: { width: \"100%\", height: \"100%\", borderRadius: Math.max(2, size.w * 0.035), display: \"flex\", flexDirection: \"column\", alignItems: \"center\", justifyContent: \"center\", gap: f * 0.4, background: cfg.backgroundColor, color: cfg.textColor, fontFamily: \"Roboto, 'Segoe UI', Arial, sans-serif\", padding: f * 0.6, boxSizing: \"border-box\", pointerEvents: \"none\", userSelect: \"none\", overflow: \"hidden\" }, children: [\n /* @__PURE__ */ (0, import_jsx_runtime.jsx)(\"div\", { style: { flexShrink: 0, background: \"#fff\", borderRadius: Math.max(2, qrSide * 0.06), padding: Math.max(2, qrSide * 0.06), lineHeight: 0 }, children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(\"img\", { src: qrUrl, alt: \"QR Code\", style: { width: `${qrSide}px`, height: `${qrSide}px`, display: \"block\" } }) }),\n /* @__PURE__ */ (0, import_jsx_runtime.jsx)(\"div\", { style: { fontSize: `${f * 1.1}px`, fontWeight: 700, textAlign: \"center\", color: cfg.accentColor, overflow: \"hidden\", textOverflow: \"ellipsis\", whiteSpace: \"nowrap\", width: \"100%\" }, children: cfg.ctaText }),\n cfg.description && /* @__PURE__ */ (0, import_jsx_runtime.jsx)(\"div\", { style: { fontSize: `${f * 0.75}px`, opacity: 0.6, textAlign: \"center\", overflow: \"hidden\", textOverflow: \"ellipsis\", whiteSpace: \"nowrap\", width: \"100%\" }, children: cfg.description })\n ] });\n}\nfunction ComingUpNextOverlay({ overlay, size }) {\n const cfg = parseConfig(overlay.content);\n if (!cfg) return null;\n const f = Math.max(8, Math.min(size.h * 0.13, size.w * 0.048));\n const showSubtitle = size.h >= 60;\n const showThumbnail = false;\n const thumbW = 0;\n return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(\"div\", { style: {\n width: \"100%\",\n height: \"100%\",\n borderRadius: Math.max(2, size.w * 0.025),\n display: \"flex\",\n background: cfg.backgroundColor,\n color: cfg.textColor,\n fontFamily: \"'Arial', 'Helvetica Neue', Helvetica, sans-serif\",\n overflow: \"hidden\",\n pointerEvents: \"none\",\n userSelect: \"none\",\n fontSize: `${f}px`,\n WebkitFontSmoothing: \"antialiased\"\n }, children: [\n /* @__PURE__ */ (0, import_jsx_runtime.jsx)(\"div\", { style: { width: Math.max(3, size.w * 0.018), flexShrink: 0, backgroundColor: cfg.accentColor } }),\n /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(\"div\", { style: {\n flex: 1,\n display: \"flex\",\n flexDirection: \"column\",\n justifyContent: \"center\",\n padding: `${f * 0.35}px ${f * 0.75}px`,\n minWidth: 0,\n gap: `${f * 0.08}px`\n }, children: [\n /* @__PURE__ */ (0, import_jsx_runtime.jsx)(\"div\", { style: {\n fontSize: \"0.7em\",\n fontWeight: 700,\n textTransform: \"uppercase\",\n letterSpacing: \"0.09em\",\n color: cfg.accentColor,\n lineHeight: 1\n }, children: \"Coming Up Next\" }),\n /* @__PURE__ */ (0, import_jsx_runtime.jsx)(\"div\", { style: {\n fontSize: \"1.2em\",\n fontWeight: 700,\n lineHeight: 1.2,\n overflow: \"hidden\",\n textOverflow: \"ellipsis\",\n whiteSpace: \"nowrap\"\n }, children: cfg.title }),\n showSubtitle && /* @__PURE__ */ (0, import_jsx_runtime.jsx)(\"div\", { style: {\n fontSize: \"0.82em\",\n opacity: 0.65,\n lineHeight: 1.1,\n overflow: \"hidden\",\n textOverflow: \"ellipsis\",\n whiteSpace: \"nowrap\"\n }, children: cfg.subtitle }),\n cfg.scheduledTime && /* @__PURE__ */ (0, import_jsx_runtime.jsx)(\"div\", { style: {\n fontSize: \"0.9em\",\n fontWeight: 700,\n color: cfg.accentColor,\n lineHeight: 1\n }, children: cfg.scheduledTime })\n ] }),\n showThumbnail && /* @__PURE__ */ (0, import_jsx_runtime.jsx)(\"div\", { style: { flexShrink: 0, width: `${thumbW}px`, overflow: \"hidden\" }, children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(\n \"img\",\n {\n src: cfg.thumbnailUrl,\n alt: \"\",\n style: { width: \"100%\", height: \"100%\", objectFit: \"cover\", display: \"block\" }\n }\n ) })\n ] });\n}\nfunction ContextualTriggerOverlay({ overlay, size }) {\n const cfg = parseConfig(overlay.content);\n if (!cfg) return null;\n const icons = { alert: \"\\u26A0\\uFE0F\", celebration: \"\\u{1F389}\", info: \"\\u2139\\uFE0F\", warning: \"\\u{1F514}\" };\n const f = Math.max(6, size.w * 0.05);\n return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(\"div\", { style: { width: \"100%\", height: \"100%\", borderRadius: Math.max(2, size.w * 0.035), display: \"flex\", alignItems: \"center\", gap: f * 0.8, padding: `0 ${f * 1.2}px`, background: cfg.backgroundColor, color: cfg.textColor, fontFamily: \"Roboto, 'Segoe UI', Arial, sans-serif\", borderLeft: `${Math.max(2, size.w * 0.02)}px solid ${cfg.accentColor}`, boxSizing: \"border-box\", pointerEvents: \"none\", userSelect: \"none\", fontSize: `${f}px` }, children: [\n /* @__PURE__ */ (0, import_jsx_runtime.jsx)(\"span\", { style: { fontSize: \"2em\", flexShrink: 0 }, children: icons[cfg.iconType] || \"\\u26A1\" }),\n /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(\"div\", { style: { flex: 1, minWidth: 0 }, children: [\n /* @__PURE__ */ (0, import_jsx_runtime.jsx)(\"div\", { style: { fontSize: \"1.3em\", fontWeight: 700, overflow: \"hidden\", textOverflow: \"ellipsis\", whiteSpace: \"nowrap\" }, children: cfg.headline }),\n /* @__PURE__ */ (0, import_jsx_runtime.jsx)(\"div\", { style: { fontSize: \"0.9em\", opacity: 0.7, overflow: \"hidden\", textOverflow: \"ellipsis\", whiteSpace: \"nowrap\" }, children: cfg.message })\n ] })\n ] });\n}\nfunction OddsBettingOverlay({ overlay, size }) {\n const cfg = parseConfig(overlay.content);\n if (!cfg) return null;\n const f = Math.max(6, size.w * 0.052);\n return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(\"div\", { style: { width: \"100%\", height: \"100%\", borderRadius: Math.max(2, size.w * 0.035), display: \"flex\", flexDirection: \"column\", padding: f * 0.8, background: cfg.backgroundColor, color: cfg.textColor, fontFamily: \"Roboto, 'Segoe UI', Arial, sans-serif\", boxSizing: \"border-box\", pointerEvents: \"none\", userSelect: \"none\", fontSize: `${f}px` }, children: [\n /* @__PURE__ */ (0, import_jsx_runtime.jsx)(\"div\", { style: { fontSize: \"0.9em\", fontWeight: 700, textTransform: \"uppercase\", letterSpacing: \"0.05em\", color: cfg.accentColor, marginBottom: f * 0.4 }, children: cfg.eventTitle }),\n /* @__PURE__ */ (0, import_jsx_runtime.jsx)(\"div\", { style: { flex: 1, display: \"flex\", flexDirection: \"column\", gap: f * 0.2, justifyContent: \"center\" }, children: (cfg.options || []).slice(0, 5).map((opt, i) => /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(\"div\", { style: { display: \"flex\", justifyContent: \"space-between\", alignItems: \"center\", padding: `${f * 0.2}px ${f * 0.6}px`, borderRadius: Math.max(2, f * 0.3), background: `${cfg.accentColor}15`, fontSize: \"1em\" }, children: [\n /* @__PURE__ */ (0, import_jsx_runtime.jsx)(\"span\", { style: { overflow: \"hidden\", textOverflow: \"ellipsis\", whiteSpace: \"nowrap\", flex: 1 }, children: opt.label }),\n /* @__PURE__ */ (0, import_jsx_runtime.jsx)(\"span\", { style: { fontWeight: 700, marginLeft: f * 0.8, flexShrink: 0, color: cfg.accentColor }, children: opt.odds })\n ] }, i)) }),\n cfg.sponsorText && /* @__PURE__ */ (0, import_jsx_runtime.jsx)(\"div\", { style: { fontSize: \"0.7em\", opacity: 0.4, textAlign: \"center\", marginTop: f * 0.4 }, children: cfg.sponsorText })\n ] });\n}\nfunction BreakingNewsOverlay({ overlay, size }) {\n const cfg = parseConfig(overlay.content);\n if (!cfg) return null;\n const urgencyColors = { breaking: \"#dc2626\", urgent: \"#ea580c\", normal: \"#2563eb\" };\n const labelBg = urgencyColors[cfg.urgency] || urgencyColors.normal;\n const label = cfg.urgency === \"breaking\" ? \"BREAKING\" : cfg.urgency === \"urgent\" ? \"URGENT\" : \"NEWS\";\n const f = Math.max(6, size.w * 0.05);\n return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(\"div\", { style: { width: \"100%\", height: \"100%\", borderRadius: Math.max(2, size.w * 0.02), display: \"flex\", alignItems: \"center\", background: cfg.backgroundColor, color: cfg.textColor, fontFamily: \"Roboto, 'Segoe UI', Arial, sans-serif\", overflow: \"hidden\", pointerEvents: \"none\", userSelect: \"none\", fontSize: `${f}px` }, children: [\n /* @__PURE__ */ (0, import_jsx_runtime.jsx)(\"div\", { style: { padding: `0 ${f * 0.8}px`, height: \"100%\", display: \"flex\", alignItems: \"center\", background: labelBg, color: \"#fff\", fontSize: \"1em\", fontWeight: 900, textTransform: \"uppercase\", letterSpacing: \"0.05em\", flexShrink: 0 }, children: label }),\n /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(\"div\", { style: { flex: 1, padding: `0 ${f * 1}px`, minWidth: 0 }, children: [\n /* @__PURE__ */ (0, import_jsx_runtime.jsx)(\"div\", { style: { fontSize: \"1.3em\", fontWeight: 700, overflow: \"hidden\", textOverflow: \"ellipsis\", whiteSpace: \"nowrap\" }, children: cfg.headline }),\n cfg.body && /* @__PURE__ */ (0, import_jsx_runtime.jsx)(\"div\", { style: { fontSize: \"0.9em\", opacity: 0.7, overflow: \"hidden\", textOverflow: \"ellipsis\", whiteSpace: \"nowrap\" }, children: cfg.body })\n ] })\n ] });\n}\nfunction calcCountdownRemaining(targetTime) {\n const diff = Math.max(0, new Date(targetTime).getTime() - Date.now());\n return {\n d: Math.floor(diff / 864e5),\n h: Math.floor(diff % 864e5 / 36e5),\n m: Math.floor(diff % 36e5 / 6e4),\n s: Math.floor(diff % 6e4 / 1e3),\n expired: diff === 0\n };\n}\nfunction CountdownOverlay({ overlay, size }) {\n const cfg = parseConfig(overlay.content);\n const targetTime = cfg?.targetTime ?? \"\";\n const [remaining, setRemaining] = (0, import_react.useState)(\n () => targetTime ? calcCountdownRemaining(targetTime) : { d: 0, h: 0, m: 0, s: 0, expired: false }\n );\n (0, import_react.useEffect)(() => {\n if (!targetTime) return;\n setRemaining(calcCountdownRemaining(targetTime));\n const id = setInterval(() => setRemaining(calcCountdownRemaining(targetTime)), 1e3);\n return () => clearInterval(id);\n }, [targetTime]);\n if (!cfg) return null;\n const f = Math.max(6, size.w * 0.055);\n const pad = (n) => String(n).padStart(2, \"0\");\n const units = [\n { show: cfg.showDays, value: pad(remaining.d), label: \"DAYS\" },\n { show: cfg.showHours, value: pad(remaining.h), label: \"HRS\" },\n { show: cfg.showMinutes, value: pad(remaining.m), label: \"MIN\" },\n { show: cfg.showSeconds, value: pad(remaining.s), label: \"SEC\" }\n ];\n return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(\"div\", { style: { width: \"100%\", height: \"100%\", borderRadius: Math.max(2, size.w * 0.035), display: \"flex\", flexDirection: \"column\", alignItems: \"center\", justifyContent: \"center\", padding: f * 0.8, background: cfg.backgroundColor, color: cfg.textColor, fontFamily: \"Roboto, 'Segoe UI', Arial, sans-serif\", boxSizing: \"border-box\", pointerEvents: \"none\", userSelect: \"none\", fontSize: `${f}px` }, children: [\n /* @__PURE__ */ (0, import_jsx_runtime.jsx)(\"div\", { style: { fontSize: \"0.8em\", fontWeight: 600, textTransform: \"uppercase\", letterSpacing: \"0.05em\", color: cfg.accentColor, marginBottom: f * 0.4 }, children: cfg.eventName }),\n remaining.expired ? /* @__PURE__ */ (0, import_jsx_runtime.jsx)(\"div\", { style: { fontSize: \"1em\", fontWeight: 700, opacity: 0.6 }, children: cfg.message || \"Event ended\" }) : /* @__PURE__ */ (0, import_jsx_runtime.jsx)(\"div\", { style: { display: \"flex\", gap: f * 0.6, alignItems: \"center\" }, children: units.filter((u) => u.show).map((u, i, arr) => /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(import_react.default.Fragment, { children: [\n /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(\"div\", { style: { textAlign: \"center\" }, children: [\n /* @__PURE__ */ (0, import_jsx_runtime.jsx)(\"div\", { style: { fontSize: \"2em\", fontWeight: 900, lineHeight: 1, borderRadius: Math.max(2, f * 0.4), padding: `${f * 0.2}px ${f * 0.4}px`, background: `${cfg.accentColor}20` }, children: u.value }),\n /* @__PURE__ */ (0, import_jsx_runtime.jsx)(\"div\", { style: { fontSize: \"0.5em\", opacity: 0.5, marginTop: f * 0.2 }, children: u.label })\n ] }),\n i < arr.length - 1 && /* @__PURE__ */ (0, import_jsx_runtime.jsx)(\"div\", { style: { fontSize: \"1.8em\", fontWeight: 700, opacity: 0.3 }, children: \":\" })\n ] }, u.label)) }),\n !remaining.expired && cfg.message && /* @__PURE__ */ (0, import_jsx_runtime.jsx)(\"div\", { style: { fontSize: \"0.8em\", opacity: 0.6, marginTop: f * 0.4, textAlign: \"center\" }, children: cfg.message })\n ] });\n}\nfunction ShapeOverlay({ overlay, size }) {\n const f = Math.max(6, size.w * 0.05);\n return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(\"div\", { style: { width: \"100%\", height: \"100%\", borderRadius: Math.max(2, size.w * 0.03), background: \"rgba(99, 102, 241, 0.2)\", border: \"2px solid rgba(99, 102, 241, 0.4)\", display: \"flex\", alignItems: \"center\", justifyContent: \"center\", pointerEvents: \"none\", userSelect: \"none\" }, children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(\"div\", { style: { fontSize: `${f}px`, fontWeight: 500, color: \"rgba(163, 163, 163, 0.8)\", textTransform: \"uppercase\" }, children: overlay.name }) });\n}\nfunction hexToRgb(hex) {\n if (!hex || !hex.startsWith(\"#\")) return \"0,0,0\";\n const clean = hex.slice(1);\n const num = parseInt(clean.length === 3 ? clean.replace(/./g, \"$&$&\") : clean, 16);\n return `${num >> 16 & 255},${num >> 8 & 255},${num & 255}`;\n}\nvar FADE_DURATION_MS = 1e3;\nvar ENTER_ANIMATION_ALIASES = {\n fade: \"fade\",\n slide_from_left: \"slide_from_left\",\n slide_from_right: \"slide_from_right\",\n slide_from_top: \"slide_from_top\",\n slide_from_bottom: \"slide_from_bottom\",\n slide_left: \"slide_from_left\",\n slide_right: \"slide_from_right\",\n slide_up: \"slide_from_top\",\n slide_down: \"slide_from_bottom\"\n};\nfunction normalizeEnterAnimation(v) {\n if (typeof v !== \"string\") return null;\n return ENTER_ANIMATION_ALIASES[v] ?? null;\n}\nfunction getEnterAnimation(overlay) {\n const flat = overlay.enter_animation;\n const fromFlat = normalizeEnterAnimation(flat);\n if (fromFlat) return fromFlat;\n if (overlay.content) {\n try {\n const parsed = JSON.parse(overlay.content);\n const fromContent = normalizeEnterAnimation(parsed?.enterAnimation);\n if (fromContent) return fromContent;\n } catch {\n }\n }\n return \"fade\";\n}\nfunction enterHiddenTransform(anim) {\n switch (anim) {\n case \"slide_from_left\":\n return \"translateX(-120%)\";\n case \"slide_from_right\":\n return \"translateX(120%)\";\n case \"slide_from_top\":\n return \"translateY(-120%)\";\n case \"slide_from_bottom\":\n return \"translateY(120%)\";\n default:\n return \"\";\n }\n}\nvar SHOWCASE_CYCLE_MS_DEFAULT = 36e3;\nvar SHOWCASE_MIN_BEAT_MS = 6e3;\nvar BEAT_POP_IN_MS = 520;\nvar BEAT_POP_OUT_MS = 520;\nvar SHOWCASE_PERSISTENT_TYPES = /* @__PURE__ */ new Set([\n \"scroller\",\n \"breaking_news\",\n \"image\",\n \"text\",\n \"shape\",\n \"countdown\",\n \"qr_code\",\n \"coming_up_next\",\n \"score_bug\"\n]);\nfunction easeOutCubic(t) {\n const u = 1 - t;\n return 1 - u * u * u;\n}\nfunction easeInCubic(t) {\n return t * t * t;\n}\nfunction easeOutBack(t) {\n const c1 = 1.70158;\n const c3 = c1 + 1;\n return 1 + c3 * (t - 1) ** 3 + c1 * (t - 1) ** 2;\n}\nfunction beatOpacity(phase, beatMs) {\n if (phase < BEAT_POP_IN_MS) return easeOutCubic(phase / BEAT_POP_IN_MS);\n const holdEnd = beatMs - BEAT_POP_OUT_MS;\n if (phase >= holdEnd) {\n return Math.max(\n 0,\n 1 - easeInCubic((phase - holdEnd) / BEAT_POP_OUT_MS)\n );\n }\n return 1;\n}\nfunction beatScale(phase, beatMs) {\n if (phase < BEAT_POP_IN_MS) {\n return Math.min(1, 0.92 + 0.08 * easeOutBack(phase / BEAT_POP_IN_MS));\n }\n const holdEnd = beatMs - BEAT_POP_OUT_MS;\n if (phase >= holdEnd) {\n return 1 - 0.06 * easeInCubic((phase - holdEnd) / BEAT_POP_OUT_MS);\n }\n return 1;\n}\nfunction partitionShowcase(overlays) {\n const visible = overlays.filter((o) => o.visible);\n const persistent = [];\n const spotlight = [];\n for (const o of visible) {\n if (SHOWCASE_PERSISTENT_TYPES.has(o.type)) persistent.push(o);\n else spotlight.push(o);\n }\n spotlight.sort(\n (a, b) => a.z_index - b.z_index || a.id - b.id\n );\n const beats = [];\n for (const o of spotlight) beats.push([o]);\n return { persistent, beats };\n}\nfunction useShowcaseBeat(enabled, cycleMs, beats) {\n const safeBeats = Math.max(1, beats);\n const beatMs = Math.max(\n SHOWCASE_MIN_BEAT_MS,\n Math.floor(cycleMs / safeBeats)\n );\n const totalMs = beatMs * safeBeats;\n const [now, setNow] = (0, import_react.useState)(() => Date.now());\n (0, import_react.useEffect)(() => {\n if (!enabled) return;\n const id = window.setInterval(() => setNow(Date.now()), 64);\n return () => clearInterval(id);\n }, [enabled]);\n const phase = now % totalMs;\n const beatIndex = Math.min(safeBeats - 1, Math.floor(phase / beatMs));\n const beatPhase = phase - beatIndex * beatMs;\n return { beatIndex, beatPhase, beatMs };\n}\nvar OverlayRenderer = ({\n overlays,\n currentTime,\n videoRef,\n coordinateSpace,\n showcaseMode = false,\n showcaseCycleMs = SHOWCASE_CYCLE_MS_DEFAULT\n}) => {\n const [dims, setDims] = (0, import_react.useState)(null);\n const rafRef = (0, import_react.useRef)(null);\n const [fadeMap, setFadeMap] = (0, import_react.useState)(/* @__PURE__ */ new Map());\n const removeTimers = (0, import_react.useRef)(/* @__PURE__ */ new Map());\n const mountTimeRef = (0, import_react.useRef)(Date.now());\n const [wallclockSec, setWallclockSec] = (0, import_react.useState)(0);\n (0, import_react.useEffect)(() => {\n if (!showcaseMode) return;\n const tick = () => setWallclockSec((Date.now() - mountTimeRef.current) / 1e3);\n tick();\n const id = window.setInterval(tick, 200);\n return () => clearInterval(id);\n }, [showcaseMode]);\n const { persistent: showcasePersistent, beats: showcaseBeats } = (0, import_react.useMemo)(\n () => partitionShowcase(overlays),\n [overlays]\n );\n const {\n beatIndex: showcaseBeatIndex,\n beatPhase: showcaseBeatPhase,\n beatMs: showcaseBeatMs\n } = useShowcaseBeat(showcaseMode, showcaseCycleMs, showcaseBeats.length);\n const showcasePersistentIds = (0, import_react.useMemo)(\n () => new Set(showcasePersistent.map((o) => o.id)),\n [showcasePersistent]\n );\n const showcaseSpotlightIds = (0, import_react.useMemo)(() => {\n const beat = showcaseBeats[showcaseBeatIndex];\n return new Set((beat ?? []).map((o) => o.id));\n }, [showcaseBeats, showcaseBeatIndex]);\n const updateDims = (0, import_react.useCallback)(() => {\n const video = videoRef.current;\n if (video) {\n const computed = computeVideoDimensions(video);\n setDims((prev) => {\n if (!computed || prev && prev.nativeWidth === computed.nativeWidth && prev.nativeHeight === computed.nativeHeight && prev.displayWidth === computed.displayWidth && prev.displayHeight === computed.displayHeight && prev.offsetX === computed.offsetX && prev.offsetY === computed.offsetY) {\n return prev;\n }\n return computed;\n });\n }\n }, [videoRef]);\n (0, import_react.useEffect)(() => {\n updateDims();\n const interval = setInterval(updateDims, 500);\n const handleResize = () => {\n if (rafRef.current) cancelAnimationFrame(rafRef.current);\n rafRef.current = requestAnimationFrame(updateDims);\n };\n window.addEventListener(\"resize\", handleResize);\n return () => {\n clearInterval(interval);\n window.removeEventListener(\"resize\", handleResize);\n if (rafRef.current) cancelAnimationFrame(rafRef.current);\n };\n }, [updateDims]);\n const activeOverlays = (0, import_react.useMemo)(() => {\n if (showcaseMode) {\n const beat = showcaseBeats[showcaseBeatIndex] ?? [];\n const scheduledPersistent = showcasePersistent.filter(\n (o) => isOverlayActive(o, wallclockSec)\n );\n return [...scheduledPersistent, ...beat];\n }\n return overlays.filter((o) => isOverlayActive(o, currentTime));\n }, [\n overlays,\n currentTime,\n wallclockSec,\n showcaseMode,\n showcasePersistent,\n showcaseBeats,\n showcaseBeatIndex\n ]);\n (0, import_react.useLayoutEffect)(() => {\n const activeIds = new Set(activeOverlays.map((o) => o.id));\n setFadeMap((prev) => {\n const next = new Map(prev);\n for (const overlay of activeOverlays) {\n if (!next.has(overlay.id)) {\n next.set(overlay.id, { overlay, visible: false });\n } else {\n const existing = next.get(overlay.id);\n next.set(overlay.id, { ...existing, overlay });\n }\n }\n for (const [id, state] of next) {\n if (!activeIds.has(id) && state.visible) {\n next.set(id, { ...state, visible: false });\n if (!removeTimers.current.has(id)) {\n const timer = setTimeout(() => {\n setFadeMap((m) => {\n const updated = new Map(m);\n updated.delete(id);\n return updated;\n });\n removeTimers.current.delete(id);\n }, FADE_DURATION_MS);\n removeTimers.current.set(id, timer);\n }\n } else if (!activeIds.has(id) && !state.visible) {\n }\n }\n return next;\n });\n }, [activeOverlays]);\n (0, import_react.useEffect)(() => {\n const toFadeIn = [];\n for (const [id, state] of fadeMap) {\n if (!state.visible) {\n const isActive = activeOverlays.some((o) => o.id === id);\n if (isActive) toFadeIn.push(id);\n }\n }\n if (toFadeIn.length === 0) return;\n const raf = requestAnimationFrame(() => {\n setFadeMap((prev) => {\n const next = new Map(prev);\n for (const id of toFadeIn) {\n const state = next.get(id);\n if (state) next.set(id, { ...state, visible: true });\n }\n return next;\n });\n });\n return () => cancelAnimationFrame(raf);\n }, [fadeMap, activeOverlays]);\n (0, import_react.useEffect)(() => {\n return () => {\n for (const timer of removeTimers.current.values()) clearTimeout(timer);\n };\n }, []);\n if (!dims || fadeMap.size === 0) return null;\n return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(\n \"div\",\n {\n \"aria-hidden\": \"true\",\n style: {\n position: \"absolute\",\n left: `${dims.offsetX}px`,\n top: `${dims.offsetY}px`,\n width: `${dims.displayWidth}px`,\n height: `${dims.displayHeight}px`,\n pointerEvents: \"none\",\n overflow: \"hidden\",\n zIndex: 8\n },\n children: [...fadeMap.values()].map(({ overlay, visible }) => {\n const scaleX = coordinateSpace?.width ? dims.displayWidth / coordinateSpace.width : dims.scaleX;\n const scaleY = coordinateSpace?.height ? dims.displayHeight / coordinateSpace.height : dims.scaleY;\n const left = overlay.x * scaleX;\n const top = overlay.y * scaleY;\n const width = overlay.width * scaleX;\n const height = overlay.height * scaleY;\n const baseOpacity = Math.max(0, Math.min(100, overlay.opacity)) / 100;\n const isShowcasePersistent = showcaseMode && showcasePersistentIds.has(overlay.id);\n const isShowcaseSpotlight = showcaseMode && showcaseSpotlightIds.has(overlay.id);\n const isShowcaseDormant = showcaseMode && !isShowcasePersistent && !isShowcaseSpotlight;\n const useShowcasePop = isShowcaseSpotlight;\n const opacity = useShowcasePop ? baseOpacity * beatOpacity(showcaseBeatPhase, showcaseBeatMs) : isShowcaseDormant ? 0 : visible ? baseOpacity : 0;\n const popScale = useShowcasePop ? beatScale(showcaseBeatPhase, showcaseBeatMs) : 1;\n const sz = { w: width, h: height };\n const enterAnim = getEnterAnimation(overlay);\n const hasSlide = enterAnim !== \"fade\" && !useShowcasePop;\n const slideTransform = hasSlide && !visible ? enterHiddenTransform(enterAnim) : \"\";\n const popTransform = showcaseMode && useShowcasePop ? `scale(${popScale})` : \"\";\n const combinedTransform = [slideTransform, popTransform].filter(Boolean).join(\" \");\n return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(\n \"div\",\n {\n style: {\n position: \"absolute\",\n left: `${left}px`,\n top: `${top}px`,\n width: `${width}px`,\n height: `${height}px`,\n opacity,\n transition: useShowcasePop ? \"none\" : hasSlide ? `opacity ${FADE_DURATION_MS}ms ease, transform ${FADE_DURATION_MS}ms cubic-bezier(0.22, 1, 0.36, 1)` : `opacity ${FADE_DURATION_MS}ms ease`,\n transform: combinedTransform || void 0,\n transformOrigin: showcaseMode && useShowcasePop ? \"center center\" : void 0,\n zIndex: overlay.z_index,\n overflow: \"hidden\"\n },\n children: [\n overlay.type === \"image\" && /* @__PURE__ */ (0, import_jsx_runtime.jsx)(ImageOverlay, { overlay }),\n overlay.type === \"text\" && /* @__PURE__ */ (0, import_jsx_runtime.jsx)(TextOverlay, { overlay }),\n overlay.type === \"scroller\" && /* @__PURE__ */ (0, import_jsx_runtime.jsx)(ScrollerOverlay, { overlay }),\n overlay.type === \"shape\" && /* @__PURE__ */ (0, import_jsx_runtime.jsx)(ShapeOverlay, { overlay, size: sz }),\n overlay.type === \"score_bug\" && /* @__PURE__ */ (0, import_jsx_runtime.jsx)(ScoreBugOverlay, { overlay, size: sz }),\n overlay.type === \"lower_third\" && /* @__PURE__ */ (0, import_jsx_runtime.jsx)(LowerThirdOverlay, { overlay, size: sz }),\n overlay.type === \"qr_code\" && /* @__PURE__ */ (0, import_jsx_runtime.jsx)(QrCodeOverlay, { overlay, size: sz }),\n overlay.type === \"coming_up_next\" && /* @__PURE__ */ (0, import_jsx_runtime.jsx)(ComingUpNextOverlay, { overlay, size: sz }),\n overlay.type === \"contextual_trigger\" && /* @__PURE__ */ (0, import_jsx_runtime.jsx)(ContextualTriggerOverlay, { overlay, size: sz }),\n overlay.type === \"odds_betting\" && /* @__PURE__ */ (0, import_jsx_runtime.jsx)(OddsBettingOverlay, { overlay, size: sz }),\n overlay.type === \"breaking_news\" && /* @__PURE__ */ (0, import_jsx_runtime.jsx)(BreakingNewsOverlay, { overlay, size: sz }),\n overlay.type === \"countdown\" && /* @__PURE__ */ (0, import_jsx_runtime.jsx)(CountdownOverlay, { overlay, size: sz })\n ]\n },\n overlay.id\n );\n })\n }\n );\n};\n\n// src/utils/adcision.ts\nvar ADCISION_API_BASE = \"https://adstorm.co/api-adstorm-dev\";\nasync function fetchAdcisionChannel(channelId, apiBaseUrl = ADCISION_API_BASE) {\n const response = await fetch(\n `${apiBaseUrl}/adstorm/adcision/channels/${channelId}`\n );\n if (!response.ok) {\n throw new Error(\n `Failed to fetch adcision channel ${channelId}: ${response.status} ${response.statusText}`\n );\n }\n return response.json();\n}\nasync function fetchAdcisionChannelLiveContext(channelId, apiBaseUrl = ADCISION_API_BASE) {\n const response = await fetch(\n `${apiBaseUrl}/adstorm/adcision/channels/${channelId}/live-context`\n );\n if (!response.ok) {\n throw new Error(\n `Failed to fetch adcision channel live context ${channelId}: ${response.status} ${response.statusText}`\n );\n }\n return response.json();\n}\n\n// src/ui/StormcloudVideoPlayer.tsx\nvar import_jsx_runtime2 = require(\"react/jsx-runtime\");\nvar CRITICAL_PROPS = [\n \"src\",\n \"allowNativeHls\",\n \"licenseKey\",\n \"lowLatencyMode\",\n \"driftToleranceMs\",\n \"debugAdTiming\"\n];\nvar CONTROLS_HIDE_DELAY = 3e3;\nvar DEFAULT_PLAYER_ASPECT_RATIO = 16 / 9;\nvar DEBUG_PANEL_MARKER_LIMIT = 12;\nvar AI_CONTEXT_FALLBACK_POLL_MS = 4e3;\nvar AI_CONTEXT_MIN_POLL_MS = 800;\nvar PANEL_BASE_RIGHT_OFFSET = 10;\nvar StormcloudVideoPlayerComponent = import_react2.default.memo(\n (props) => {\n const {\n src,\n autoplay,\n muted,\n lowLatencyMode,\n allowNativeHls,\n driftToleranceMs,\n immediateManifestAds,\n debugAdTiming,\n showCustomControls,\n hideLoadingIndicator,\n onVolumeToggle,\n onFullscreenToggle,\n onControlClick,\n onReady,\n wrapperClassName,\n wrapperStyle,\n className,\n style,\n controls,\n playsInline,\n preload,\n poster,\n children,\n licenseKey,\n minSegmentsBeforePlay,\n disableAds,\n disableFiller,\n swirlProjectId,\n swirlShowcaseDemo,\n swirlOverlayApiBaseUrl,\n swirlOverlayCoordinateSpace,\n adcisionChannelId,\n disableOverlays,\n showAdsControl,\n showOverlaysControl,\n showAiContextControl,\n showDebugControl,\n ...restVideoAttrs\n } = props;\n const [adcisionSrc, setAdcisionSrc] = (0, import_react2.useState)(null);\n const videoRef = (0, import_react2.useRef)(null);\n const playerRef = (0, import_react2.useRef)(null);\n const bufferingTimeoutRef = (0, import_react2.useRef)(null);\n const controlsTimerRef = (0, import_react2.useRef)(null);\n const wrapperRef = (0, import_react2.useRef)(null);\n const [adStatus, setAdStatus] = import_react2.default.useState({ showAds: false, inAdBreak: false, currentIndex: 0, totalAds: 0, remainingSeconds: 0 });\n const [shouldShowNativeControls, setShouldShowNativeControls] = import_react2.default.useState(true);\n const [isMuted, setIsMuted] = import_react2.default.useState(false);\n const [isFullscreen, setIsFullscreen] = import_react2.default.useState(false);\n const [isPlaying, setIsPlaying] = import_react2.default.useState(false);\n const [currentTime, setCurrentTime] = import_react2.default.useState(0);\n const [duration, setDuration] = import_react2.default.useState(0);\n const [volume, setVolume] = import_react2.default.useState(1);\n const [playbackRate, setPlaybackRate] = import_react2.default.useState(1);\n const [showVolumeSlider, setShowVolumeSlider] = import_react2.default.useState(false);\n const [showSpeedMenu, setShowSpeedMenu] = import_react2.default.useState(false);\n const [isLoading, setIsLoading] = import_react2.default.useState(true);\n const [isBuffering, setIsBuffering] = import_react2.default.useState(false);\n const [showCenterPlay, setShowCenterPlay] = import_react2.default.useState(false);\n const [showLicenseWarning, setShowLicenseWarning] = import_react2.default.useState(false);\n const [controlsVisible, setControlsVisible] = import_react2.default.useState(true);\n const [overlays, setOverlays] = import_react2.default.useState([]);\n const overlayApiBase = import_react2.default.useMemo(\n () => swirlOverlayApiBaseUrl?.replace(/\\/$/, \"\") || OVERLAY_API_BASE,\n [swirlOverlayApiBaseUrl]\n );\n const [overlayCoordSpace, setOverlayCoordSpace] = import_react2.default.useState(null);\n const displayOverlays = overlays;\n const [viewportWidth, setViewportWidth] = import_react2.default.useState(\n typeof window !== \"undefined\" ? window.innerWidth : 1920\n );\n const [isPortrait, setIsPortrait] = import_react2.default.useState(\n typeof window !== \"undefined\" ? window.innerHeight > window.innerWidth : false\n );\n const [playerAspectRatio, setPlayerAspectRatio] = import_react2.default.useState(\n DEFAULT_PLAYER_ASPECT_RATIO\n );\n const [showDebugPanel, setShowDebugPanel] = import_react2.default.useState(false);\n const [debugMarkers, setDebugMarkers] = import_react2.default.useState([]);\n const [showAiPanel, setShowAiPanel] = import_react2.default.useState(false);\n const [adsDisabled, setAdsDisabled] = import_react2.default.useState(disableAds ?? false);\n const [overlaysDisabled, setOverlaysDisabled] = import_react2.default.useState(disableOverlays ?? false);\n const [aiLiveContext, setAiLiveContext] = import_react2.default.useState({\n context: null,\n isLoading: false,\n error: null,\n lastPolledAt: null\n });\n const getResponsiveScale = () => {\n if (viewportWidth < 480) return 0.7;\n if (viewportWidth < 768) return 0.8;\n if (viewportWidth < 1024) return 0.9;\n return 1;\n };\n const responsiveScale = getResponsiveScale();\n const formatDebugClock = (timestampMs) => {\n try {\n const localTimeZone = Intl.DateTimeFormat().resolvedOptions().timeZone;\n return new Date(timestampMs).toLocaleTimeString(\"en-GB\", {\n hour12: false,\n hour: \"2-digit\",\n minute: \"2-digit\",\n second: \"2-digit\",\n timeZone: localTimeZone\n });\n } catch {\n return \"--:--:--\";\n }\n };\n const formatAdInsertionEvent = (event) => {\n switch (event) {\n case \"api_response\":\n return { label: \"API\", color: \"#60a5fa\" };\n case \"scte35_inserted\":\n return { label: \"SCTE-35\", color: \"#f43f5e\" };\n case \"segment_found\":\n return { label: \"FOUND\", color: \"#a78bfa\" };\n case \"segment_playing\":\n return { label: \"PLAYING\", color: \"#fbbf24\" };\n case \"ad_scheduled\":\n return { label: \"SCHED\", color: \"#fb923c\" };\n case \"ad_triggered\":\n return { label: \"TRIGGER\", color: \"#34d399\" };\n default:\n return { label: event, color: \"rgba(255,255,255,0.68)\" };\n }\n };\n const formatAiRelativeTime = (timestamp) => {\n const epochMs = Date.parse(timestamp);\n if (!Number.isFinite(epochMs)) return \"unknown\";\n const diffSec = Math.max(0, Math.floor((Date.now() - epochMs) / 1e3));\n if (diffSec < 5) return \"just now\";\n if (diffSec < 60) return `${diffSec}s ago`;\n const diffMin = Math.floor(diffSec / 60);\n if (diffMin < 60) return `${diffMin}m ago`;\n const diffHr = Math.floor(diffMin / 60);\n if (diffHr < 24) return `${diffHr}h ago`;\n return `${Math.floor(diffHr / 24)}d ago`;\n };\n const resetControlsTimer = (0, import_react2.useCallback)(() => {\n if (controlsTimerRef.current) {\n clearTimeout(controlsTimerRef.current);\n }\n setControlsVisible(true);\n controlsTimerRef.current = window.setTimeout(() => {\n if (!showVolumeSlider && !showSpeedMenu) {\n setControlsVisible(false);\n }\n }, CONTROLS_HIDE_DELAY);\n }, [showVolumeSlider, showSpeedMenu]);\n const formatTime = (seconds) => {\n if (!isFinite(seconds)) return \"0:00:00\";\n const hours = Math.floor(seconds / 3600);\n const minutes = Math.floor(seconds % 3600 / 60);\n const remainingSeconds = Math.floor(seconds % 60);\n return `${hours}:${minutes.toString().padStart(2, \"0\")}:${remainingSeconds.toString().padStart(2, \"0\")}`;\n };\n const handlePlayPause = () => {\n if (videoRef.current) {\n if (videoRef.current.paused) {\n const hasValidSource = videoRef.current.src || videoRef.current.currentSrc && videoRef.current.currentSrc !== \"\" || videoRef.current.readyState >= 1;\n if (hasValidSource) {\n videoRef.current.play()?.catch((error) => {\n console.error(\"[StormcloudVideoPlayer] Failed to play:\", error);\n });\n setShowCenterPlay(false);\n }\n } else {\n videoRef.current.pause();\n setShowCenterPlay(true);\n }\n }\n resetControlsTimer();\n };\n const handleCenterPlayClick = () => {\n if (videoRef.current && videoRef.current.paused) {\n const hasValidSource = videoRef.current.src || videoRef.current.currentSrc && videoRef.current.currentSrc !== \"\" || videoRef.current.readyState >= 1;\n if (hasValidSource) {\n videoRef.current.play()?.catch((error) => {\n console.error(\"[StormcloudVideoPlayer] Failed to play:\", error);\n });\n setShowCenterPlay(false);\n }\n }\n };\n const handleTimelineSeek = (e) => {\n if (videoRef.current && duration > 0 && isFinite(duration)) {\n const rect = e.currentTarget.getBoundingClientRect();\n const clickX = e.clientX - rect.left;\n const progress = Math.max(0, Math.min(1, clickX / rect.width));\n const newTime = progress * duration;\n if (isFinite(newTime) && newTime >= 0 && newTime <= duration) {\n videoRef.current.currentTime = newTime;\n }\n }\n resetControlsTimer();\n };\n const handleVolumeChange = (newVolume) => {\n if (playerRef.current && isFinite(newVolume)) {\n const clampedVolume = Math.max(0, Math.min(1, newVolume));\n playerRef.current.setVolume(clampedVolume);\n }\n };\n const handlePlaybackRateChange = (rate) => {\n if (videoRef.current && isFinite(rate) && rate > 0) {\n videoRef.current.playbackRate = rate;\n }\n setShowSpeedMenu(false);\n };\n const analyzerPanelWidth = Math.min(420, Math.max(320, viewportWidth * 0.41));\n const analyzerPanelHeight = isPortrait ? \"52vh\" : \"420px\";\n const analyzerPanelMaxHeight = \"60vh\";\n const panelGap = Math.max(8, 12 * responsiveScale);\n const shouldStackPanels = isPortrait || viewportWidth < 980;\n const panelBaseRight = PANEL_BASE_RIGHT_OFFSET * responsiveScale;\n const debugPanelRightOffset = showAiPanel && !shouldStackPanels ? panelBaseRight + analyzerPanelWidth + panelGap : panelBaseRight;\n (0, import_react2.useEffect)(() => {\n if (!adcisionChannelId) {\n setAdcisionSrc(null);\n return;\n }\n let cancelled = false;\n fetchAdcisionChannel(adcisionChannelId).then((ch) => {\n if (!cancelled) setAdcisionSrc(ch.stream_url);\n }).catch((err) => {\n if (!cancelled) {\n console.warn(\"[StormcloudVideoPlayer] Failed to fetch adcision channel:\", err);\n }\n });\n return () => {\n cancelled = true;\n };\n }, [adcisionChannelId]);\n const effectiveSrc = adcisionChannelId ? adcisionSrc : src;\n const isHlsStream = effectiveSrc?.toLowerCase().includes(\".m3u8\") || effectiveSrc?.toLowerCase().includes(\"/hls/\");\n const shouldShowEnhancedControls = showCustomControls && (isHlsStream ? allowNativeHls : true);\n const debugPanelBottomOffset = shouldShowEnhancedControls ? Math.max(74, 92 * responsiveScale) : Math.max(52, 58 * responsiveScale);\n const criticalPropsKey = (0, import_react2.useMemo)(() => {\n const baseParts = CRITICAL_PROPS.map(\n (prop) => prop === \"src\" ? `src:${effectiveSrc}` : `${prop}:${props[prop]}`\n ).join(\"|\");\n return `${baseParts}|adcisionChannelId:${adcisionChannelId ?? \"\"}`;\n }, [\n effectiveSrc,\n allowNativeHls,\n licenseKey,\n lowLatencyMode,\n driftToleranceMs,\n adcisionChannelId,\n debugAdTiming\n ]);\n (0, import_react2.useEffect)(() => {\n if (typeof window === \"undefined\") return;\n const el = videoRef.current;\n if (!el || !effectiveSrc) return;\n if (!licenseKey) {\n setShowLicenseWarning(true);\n setIsLoading(false);\n return;\n }\n setShowLicenseWarning(false);\n if (playerRef.current) {\n try {\n playerRef.current.destroy();\n } catch {\n }\n playerRef.current = null;\n }\n const cfg = {\n src: effectiveSrc,\n videoElement: el\n };\n if (autoplay !== void 0) cfg.autoplay = autoplay;\n if (muted !== void 0) cfg.muted = muted;\n if (lowLatencyMode !== void 0) cfg.lowLatencyMode = lowLatencyMode;\n if (allowNativeHls !== void 0) cfg.allowNativeHls = allowNativeHls;\n if (driftToleranceMs !== void 0)\n cfg.driftToleranceMs = driftToleranceMs;\n if (immediateManifestAds !== void 0)\n cfg.immediateManifestAds = immediateManifestAds;\n if (debugAdTiming !== void 0) cfg.debugAdTiming = debugAdTiming;\n if (showCustomControls !== void 0)\n cfg.showCustomControls = showCustomControls;\n if (onVolumeToggle !== void 0) cfg.onVolumeToggle = onVolumeToggle;\n if (onFullscreenToggle !== void 0)\n cfg.onFullscreenToggle = onFullscreenToggle;\n if (onControlClick !== void 0) cfg.onControlClick = onControlClick;\n if (licenseKey !== void 0) cfg.licenseKey = licenseKey;\n if (minSegmentsBeforePlay !== void 0)\n cfg.minSegmentsBeforePlay = minSegmentsBeforePlay;\n if (disableAds !== void 0) cfg.disableAds = disableAds;\n cfg.disableFiller = disableFiller ?? true;\n if (adcisionChannelId !== void 0) {\n cfg.projectId = String(adcisionChannelId);\n cfg.channelId = adcisionChannelId;\n } else if (swirlProjectId !== void 0)\n cfg.projectId = String(swirlProjectId);\n const player = new StormcloudVideoPlayer(cfg);\n playerRef.current = player;\n player.load().then(() => {\n const showNative = player.shouldShowNativeControls();\n setShouldShowNativeControls(showNative);\n onReady?.(player);\n }).catch((error) => {\n console.error(\n \"StormcloudVideoPlayer: Failed to load player:\",\n error\n );\n setIsLoading(false);\n onReady?.(player);\n });\n return () => {\n try {\n player.destroy();\n } catch {\n }\n playerRef.current = null;\n };\n }, [criticalPropsKey]);\n (0, import_react2.useEffect)(() => {\n if (!swirlProjectId || adcisionChannelId) {\n setOverlays([]);\n setOverlayCoordSpace(null);\n return;\n }\n let cancelled = false;\n const loadOverlays = () => {\n fetchProjectOverlays(swirlProjectId, overlayApiBase).then((data) => {\n if (!cancelled) setOverlays(data);\n }).catch((err) => {\n if (!cancelled) {\n console.warn(\"[StormcloudVideoPlayer] Failed to fetch overlays:\", err);\n }\n });\n };\n loadOverlays();\n const interval = window.setInterval(loadOverlays, 25e3);\n return () => {\n cancelled = true;\n clearInterval(interval);\n };\n }, [swirlProjectId, adcisionChannelId, overlayApiBase]);\n (0, import_react2.useEffect)(() => {\n if (!swirlProjectId) return;\n const tryResolve = () => {\n const fixed = swirlOverlayCoordinateSpace;\n if (fixed && fixed.width > 0 && fixed.height > 0) {\n console.debug(\n \"[StormcloudVideoPlayer] overlay coord space (prop):\",\n fixed.width,\n \"x\",\n fixed.height\n );\n setOverlayCoordSpace({ width: fixed.width, height: fixed.height });\n return true;\n }\n const player = playerRef.current;\n if (!player) return false;\n const minRes = player.getMinHlsResolution?.();\n if (minRes && minRes.width > 0 && minRes.height > 0) {\n console.debug(\n \"[StormcloudVideoPlayer] overlay coord space (minHlsResolution):\",\n minRes.width,\n \"x\",\n minRes.height\n );\n setOverlayCoordSpace({ width: minRes.width, height: minRes.height });\n return true;\n }\n const video2 = player.videoElement;\n if (video2 && video2.videoWidth > 0 && video2.videoHeight > 0) {\n console.debug(\n \"[StormcloudVideoPlayer] overlay coord space (videoNative):\",\n video2.videoWidth,\n \"x\",\n video2.videoHeight\n );\n setOverlayCoordSpace({\n width: video2.videoWidth,\n height: video2.videoHeight\n });\n return true;\n }\n return false;\n };\n let attempts = 0;\n const maxAttempts = 40;\n tryResolve();\n const interval = setInterval(() => {\n attempts++;\n if (!swirlOverlayCoordinateSpace) {\n tryResolve();\n }\n if (attempts >= maxAttempts) clearInterval(interval);\n }, 300);\n const onVideoDims = () => {\n if (!swirlOverlayCoordinateSpace) {\n tryResolve();\n }\n };\n const video = playerRef.current?.videoElement;\n video?.addEventListener(\"loadedmetadata\", onVideoDims);\n return () => {\n clearInterval(interval);\n video?.removeEventListener(\"loadedmetadata\", onVideoDims);\n };\n }, [swirlProjectId, criticalPropsKey, swirlOverlayCoordinateSpace]);\n (0, import_react2.useEffect)(() => {\n if (!playerRef.current) return;\n try {\n if (autoplay !== void 0 && playerRef.current.videoElement) {\n playerRef.current.videoElement.autoplay = autoplay;\n }\n if (muted !== void 0 && !playerRef.current.isShowingAds()) {\n playerRef.current.setMuted(muted);\n }\n } catch (error) {\n console.warn(\"Failed to update player properties:\", error);\n }\n }, [autoplay, muted]);\n (0, import_react2.useEffect)(() => {\n if (!playerRef.current) return;\n const checkAdStatus = () => {\n if (playerRef.current) {\n const showAdsFromMethod = playerRef.current.isShowingAds();\n const showAdsFromAttribute = videoRef.current?.dataset?.stormcloudAdPlaying === \"true\";\n const showAds = showAdsFromMethod || showAdsFromAttribute;\n const inAdBreak = playerRef.current.isInAdBreak?.() ?? showAds;\n const currentIndex = playerRef.current.getCurrentAdIndex();\n const totalAds = playerRef.current.getTotalAdsInBreak();\n const remainingSeconds = playerRef.current.getRemainingAdSeconds();\n setAdStatus((prev) => {\n if (prev.showAds !== showAds || prev.inAdBreak !== inAdBreak || prev.currentIndex !== currentIndex || prev.totalAds !== totalAds || prev.remainingSeconds !== remainingSeconds) {\n if (showAds && !prev.showAds) {\n setShowCenterPlay(false);\n }\n return {\n showAds,\n inAdBreak,\n currentIndex,\n totalAds,\n remainingSeconds\n };\n }\n return prev;\n });\n }\n };\n const interval = setInterval(checkAdStatus, 50);\n return () => clearInterval(interval);\n }, []);\n (0, import_react2.useEffect)(() => {\n if (typeof window === \"undefined\" || !playerRef.current) return;\n const handleResize = () => {\n if (playerRef.current && videoRef.current) {\n if (typeof playerRef.current.resize === \"function\") {\n playerRef.current.resize();\n }\n }\n setViewportWidth(window.innerWidth);\n setIsPortrait(window.innerHeight > window.innerWidth);\n };\n window.addEventListener(\"resize\", handleResize);\n return () => window.removeEventListener(\"resize\", handleResize);\n }, []);\n (0, import_react2.useEffect)(() => {\n if (!playerRef.current || !videoRef.current) return;\n const updateStates = () => {\n if (playerRef.current && videoRef.current) {\n setIsMuted(playerRef.current.isMuted());\n setIsPlaying(!videoRef.current.paused);\n const currentTimeValue = videoRef.current.currentTime;\n setCurrentTime(isFinite(currentTimeValue) ? currentTimeValue : 0);\n const durationValue = videoRef.current.duration;\n setDuration(isFinite(durationValue) ? durationValue : 0);\n const volumeValue = playerRef.current.getVolume();\n setVolume(\n isFinite(volumeValue) ? Math.max(0, Math.min(1, volumeValue)) : 1\n );\n const rateValue = videoRef.current.playbackRate;\n setPlaybackRate(\n isFinite(rateValue) && rateValue > 0 ? rateValue : 1\n );\n }\n setIsFullscreen(\n document.fullscreenElement === wrapperRef.current\n );\n };\n const interval = setInterval(updateStates, 200);\n const handleFullscreenChange = () => {\n setIsFullscreen(\n document.fullscreenElement === wrapperRef.current\n );\n };\n document.addEventListener(\"fullscreenchange\", handleFullscreenChange);\n return () => {\n clearInterval(interval);\n document.removeEventListener(\n \"fullscreenchange\",\n handleFullscreenChange\n );\n };\n }, []);\n (0, import_react2.useEffect)(() => {\n if (!videoRef.current) return;\n const handleLoadedMetadata = () => {\n const video2 = videoRef.current;\n if (!video2) return;\n if (video2.videoWidth > 0 && video2.videoHeight > 0) {\n setPlayerAspectRatio(video2.videoWidth / video2.videoHeight);\n }\n };\n const handleCanPlay = () => {\n setIsLoading(false);\n if (bufferingTimeoutRef.current) {\n clearTimeout(bufferingTimeoutRef.current);\n bufferingTimeoutRef.current = null;\n }\n setIsBuffering(false);\n };\n const handleCanPlayThrough = () => {\n setIsLoading(false);\n if (bufferingTimeoutRef.current) {\n clearTimeout(bufferingTimeoutRef.current);\n bufferingTimeoutRef.current = null;\n }\n setIsBuffering(false);\n };\n const handleWaiting = () => {\n if (bufferingTimeoutRef.current) {\n clearTimeout(bufferingTimeoutRef.current);\n }\n bufferingTimeoutRef.current = window.setTimeout(() => {\n setIsBuffering(true);\n }, 300);\n };\n const handlePlaying = () => {\n setIsLoading(false);\n if (bufferingTimeoutRef.current) {\n clearTimeout(bufferingTimeoutRef.current);\n bufferingTimeoutRef.current = null;\n }\n setIsBuffering(false);\n setShowCenterPlay(false);\n };\n const handlePause = () => {\n const isAdActive = playerRef.current?.isShowingAds() || videoRef.current?.dataset?.stormcloudAdPlaying === \"true\";\n if (playerRef.current && !isAdActive) {\n setShowCenterPlay(true);\n } else {\n setShowCenterPlay(false);\n }\n };\n const handleEnded = () => {\n setShowCenterPlay(true);\n };\n const video = videoRef.current;\n handleLoadedMetadata();\n video.addEventListener(\"loadedmetadata\", handleLoadedMetadata);\n video.addEventListener(\"canplay\", handleCanPlay);\n video.addEventListener(\"canplaythrough\", handleCanPlayThrough);\n video.addEventListener(\"waiting\", handleWaiting);\n video.addEventListener(\"playing\", handlePlaying);\n video.addEventListener(\"pause\", handlePause);\n video.addEventListener(\"ended\", handleEnded);\n if (video.paused) {\n setShowCenterPlay(true);\n }\n return () => {\n if (bufferingTimeoutRef.current) {\n clearTimeout(bufferingTimeoutRef.current);\n bufferingTimeoutRef.current = null;\n }\n video.removeEventListener(\"loadedmetadata\", handleLoadedMetadata);\n video.removeEventListener(\"canplay\", handleCanPlay);\n video.removeEventListener(\"canplaythrough\", handleCanPlayThrough);\n video.removeEventListener(\"waiting\", handleWaiting);\n video.removeEventListener(\"playing\", handlePlaying);\n video.removeEventListener(\"pause\", handlePause);\n video.removeEventListener(\"ended\", handleEnded);\n };\n }, [debugAdTiming]);\n (0, import_react2.useEffect)(() => {\n setPlayerAspectRatio(DEFAULT_PLAYER_ASPECT_RATIO);\n }, [src]);\n (0, import_react2.useEffect)(() => {\n return () => {\n if (controlsTimerRef.current) {\n clearTimeout(controlsTimerRef.current);\n }\n };\n }, []);\n (0, import_react2.useEffect)(() => {\n if (!debugAdTiming) {\n setShowDebugPanel(false);\n setDebugMarkers([]);\n return;\n }\n const updateDebugData = () => {\n const player = playerRef.current;\n if (!player) return;\n setDebugMarkers(\n player.getAdInsertionDebugLog().slice(-DEBUG_PANEL_MARKER_LIMIT).reverse()\n );\n };\n updateDebugData();\n const interval = window.setInterval(updateDebugData, 500);\n return () => clearInterval(interval);\n }, [debugAdTiming, criticalPropsKey]);\n (0, import_react2.useEffect)(() => {\n if (!swirlProjectId || adcisionChannelId) {\n setShowAiPanel(false);\n setAiLiveContext({\n context: null,\n isLoading: false,\n error: null,\n lastPolledAt: null\n });\n }\n }, [swirlProjectId, adcisionChannelId]);\n (0, import_react2.useEffect)(() => {\n if (!showAiPanel || !swirlProjectId && !adcisionChannelId) return;\n let cancelled = false;\n let pollTimeoutId = null;\n let inFlight = false;\n const pollLiveContext = async () => {\n if (cancelled || inFlight) return;\n inFlight = true;\n setAiLiveContext((prev) => ({\n ...prev,\n isLoading: prev.context == null,\n error: null\n }));\n try {\n let payload;\n if (adcisionChannelId) {\n const adcisionCtx = await fetchAdcisionChannelLiveContext(adcisionChannelId);\n payload = {\n id: adcisionCtx.id,\n project_id: adcisionCtx.channel_id,\n keywords: adcisionCtx.keywords,\n context: adcisionCtx.context,\n updated_at: adcisionCtx.updated_at\n };\n } else {\n const response = await fetch(\n `https://adstorm.co/api-adstorm-dev/adstorm/swirl/projects/${swirlProjectId}/live-context`,\n {\n method: \"GET\",\n headers: {\n Accept: \"application/json\"\n }\n }\n );\n if (!response.ok) {\n throw new Error(\n `Live context request failed (${response.status} ${response.statusText})`\n );\n }\n payload = await response.json();\n }\n if (cancelled) return;\n setAiLiveContext({\n context: payload,\n isLoading: false,\n error: null,\n lastPolledAt: Date.now()\n });\n } catch (error) {\n if (cancelled) return;\n const message = error instanceof Error ? error.message : \"Unable to load AI live context.\";\n setAiLiveContext((prev) => ({\n ...prev,\n isLoading: false,\n error: message,\n lastPolledAt: Date.now()\n }));\n } finally {\n inFlight = false;\n if (!cancelled) {\n const segmentPollMs = playerRef.current?.getCurrentHlsSegmentDurationMs() ?? AI_CONTEXT_FALLBACK_POLL_MS;\n const nextPollMs = Math.max(AI_CONTEXT_MIN_POLL_MS, segmentPollMs);\n pollTimeoutId = window.setTimeout(pollLiveContext, nextPollMs);\n }\n }\n };\n pollLiveContext();\n return () => {\n cancelled = true;\n if (pollTimeoutId != null) {\n clearTimeout(pollTimeoutId);\n }\n };\n }, [showAiPanel, swirlProjectId, adcisionChannelId, criticalPropsKey]);\n const handleWrapperMouseMove = (0, import_react2.useCallback)(() => {\n resetControlsTimer();\n }, [resetControlsTimer]);\n const handleWrapperMouseLeave = (0, import_react2.useCallback)(() => {\n if (!showVolumeSlider && !showSpeedMenu) {\n setControlsVisible(false);\n }\n }, [showVolumeSlider, showSpeedMenu]);\n const progressPercent = duration > 0 ? currentTime / duration * 100 : 0;\n const VolumeIcon = isMuted || volume === 0 ? import_fa.FaVolumeMute : volume < 0.5 ? import_fa.FaVolumeDown : import_fa.FaVolumeUp;\n return /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)(import_jsx_runtime2.Fragment, { children: [\n /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(\"style\", { children: `\n @keyframes sc-spin {\n from { transform: rotate(0deg); }\n to { transform: rotate(360deg); }\n }\n @keyframes sc-loading-glow {\n 0%, 100% { opacity: 0.85; transform: scale(1); }\n 50% { opacity: 1; transform: scale(1.05); }\n }\n @keyframes sc-pulse {\n 0%, 100% { opacity: 1; }\n 50% { opacity: 0.6; }\n }\n @keyframes sc-fade-in {\n from { opacity: 0; transform: translateY(8px); }\n to { opacity: 1; transform: translateY(0); }\n }\n .sc-wrapper:fullscreen,\n .sc-wrapper:has(*:fullscreen) {\n border-radius: 0 !important;\n box-shadow: none !important;\n width: 100vw !important;\n height: 100vh !important;\n max-width: 100vw !important;\n max-height: 100vh !important;\n position: fixed !important;\n top: 0 !important;\n left: 0 !important;\n z-index: 999999 !important;\n background: #000 !important;\n display: flex !important;\n align-items: center !important;\n justify-content: center !important;\n }\n .sc-ctrl-btn {\n background: none;\n border: none;\n color: #fff;\n cursor: pointer;\n display: flex;\n align-items: center;\n justify-content: center;\n border-radius: 50%;\n padding: 8px;\n transition: background 0.15s ease, opacity 0.15s ease;\n opacity: 0.9;\n }\n .sc-ctrl-btn:hover {\n opacity: 1;\n background: rgba(255, 255, 255, 0.1);\n }\n .sc-ctrl-btn:active {\n opacity: 0.7;\n }\n .sc-controls-bar {\n transition: opacity 0.35s ease, transform 0.35s ease;\n }\n .sc-progress-track:hover .sc-progress-thumb {\n transform: translate(-50%, -50%) scale(1) !important;\n }\n .sc-loading-hidden .sc-loading-indicator {\n display: none !important;\n }\n .sc-debug-scroll::-webkit-scrollbar {\n width: 8px;\n }\n .sc-debug-scroll::-webkit-scrollbar-thumb {\n background: rgba(255, 255, 255, 0.22);\n border-radius: 4px;\n }\n .sc-debug-scroll {\n overflow-x: hidden !important;\n }\n .sc-ai-scroll::-webkit-scrollbar {\n width: 8px;\n }\n .sc-ai-scroll::-webkit-scrollbar-thumb {\n background: rgba(236, 72, 153, 0.34);\n border-radius: 4px;\n }\n .sc-ai-scroll {\n overflow-x: hidden !important;\n }\n ` }),\n /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)(\n \"div\",\n {\n ref: wrapperRef,\n className: `sc-wrapper ${wrapperClassName || \"\"}`,\n onMouseMove: handleWrapperMouseMove,\n onMouseLeave: handleWrapperMouseLeave,\n style: {\n display: \"flex\",\n alignItems: \"center\",\n justifyContent: \"center\",\n position: isFullscreen ? \"fixed\" : \"relative\",\n top: isFullscreen ? 0 : void 0,\n left: isFullscreen ? 0 : void 0,\n overflow: \"hidden\",\n width: isFullscreen ? \"100vw\" : \"100%\",\n height: isFullscreen ? \"100vh\" : \"auto\",\n minHeight: isFullscreen ? \"100vh\" : \"auto\",\n aspectRatio: isFullscreen ? void 0 : playerAspectRatio,\n maxWidth: isFullscreen ? \"100vw\" : \"100%\",\n maxHeight: isFullscreen ? \"100vh\" : \"none\",\n zIndex: isFullscreen ? 999999 : void 0,\n backgroundColor: \"#000\",\n borderRadius: isFullscreen ? 0 : void 0,\n boxShadow: isFullscreen ? \"none\" : void 0,\n ...wrapperStyle\n },\n children: [\n /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(\n \"video\",\n {\n ref: videoRef,\n className,\n style: {\n position: \"relative\",\n zIndex: 1,\n display: \"block\",\n width: \"100%\",\n height: \"100%\",\n maxWidth: \"100%\",\n maxHeight: isFullscreen ? \"100%\" : \"none\",\n objectFit: isFullscreen ? \"cover\" : \"contain\",\n backgroundColor: \"#000\",\n aspectRatio: isFullscreen ? \"unset\" : void 0,\n ...style\n },\n controls: shouldShowNativeControls && controls && !showCustomControls,\n playsInline,\n preload,\n poster,\n ...restVideoAttrs,\n children\n }\n ),\n displayOverlays.length > 0 && !adStatus.showAds && !overlaysDisabled && overlayCoordSpace && /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(\n OverlayRenderer,\n {\n overlays: displayOverlays,\n currentTime,\n videoRef,\n coordinateSpace: overlayCoordSpace,\n showcaseMode: !!swirlShowcaseDemo\n }\n ),\n (isLoading || isBuffering) && !hideLoadingIndicator && /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)(\n \"div\",\n {\n className: \"sc-loading-indicator\",\n style: {\n position: \"absolute\",\n top: \"50%\",\n left: \"50%\",\n transform: \"translate(-50%, -50%)\",\n zIndex: 20,\n width: `${Math.max(34, 38 * responsiveScale)}px`,\n height: `${Math.max(34, 38 * responsiveScale)}px`,\n display: \"flex\",\n alignItems: \"center\",\n justifyContent: \"center\",\n animation: \"sc-loading-glow 1.4s ease-in-out infinite\",\n filter: \"drop-shadow(0 6px 14px rgba(0, 0, 0, 0.55))\"\n },\n children: [\n /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(\n \"div\",\n {\n style: {\n position: \"absolute\",\n inset: 0,\n borderRadius: \"50%\",\n border: \"3px solid rgba(255, 255, 255, 0.25)\",\n borderTopColor: \"#ff0000\",\n borderRightColor: \"rgba(255, 255, 255, 0.85)\",\n animation: \"sc-spin 0.8s linear infinite\"\n }\n }\n ),\n /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(\n \"div\",\n {\n style: {\n width: \"7px\",\n height: \"7px\",\n borderRadius: \"50%\",\n background: \"#ff0000\",\n boxShadow: \"0 0 10px rgba(255, 0, 0, 0.65)\"\n }\n }\n )\n ]\n }\n ),\n showLicenseWarning && /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)(\n \"div\",\n {\n style: {\n position: \"absolute\",\n top: \"50%\",\n left: \"50%\",\n transform: \"translate(-50%, -50%)\",\n zIndex: 25,\n background: \"rgba(220, 38, 38, 0.92)\",\n backdropFilter: \"blur(24px)\",\n color: \"white\",\n padding: \"28px 36px\",\n borderRadius: \"14px\",\n border: \"1px solid rgba(255, 255, 255, 0.15)\",\n boxShadow: \"0 24px 64px rgba(0, 0, 0, 0.5)\",\n textAlign: \"center\",\n maxWidth: \"400px\",\n margin: \"0 16px\"\n },\n children: [\n /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(\"div\", { style: { fontSize: \"18px\", fontWeight: \"700\", marginBottom: \"10px\", letterSpacing: \"-0.02em\" }, children: \"License Key Required\" }),\n /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)(\"div\", { style: { fontSize: \"13px\", lineHeight: \"1.6\", color: \"rgba(255, 255, 255, 0.85)\" }, children: [\n \"Please provide a valid license key to use the Stormcloud Video Player.\",\n /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(\"br\", {}),\n \"Contact your administrator for licensing information.\"\n ] })\n ]\n }\n ),\n showCenterPlay && !isLoading && !isBuffering && !showLicenseWarning && !adStatus.showAds && /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(\n \"div\",\n {\n onClick: handleCenterPlayClick,\n style: {\n position: \"absolute\",\n top: \"50%\",\n left: \"50%\",\n transform: \"translate(-50%, -50%)\",\n zIndex: 15,\n cursor: \"pointer\",\n background: \"rgba(0, 0, 0, 0.55)\",\n backdropFilter: \"blur(20px)\",\n WebkitBackdropFilter: \"blur(20px)\",\n borderRadius: \"50%\",\n width: `${Math.max(64, 80 * responsiveScale)}px`,\n height: `${Math.max(64, 80 * responsiveScale)}px`,\n display: \"flex\",\n alignItems: \"center\",\n justifyContent: \"center\",\n border: \"1.5px solid rgba(255, 255, 255, 0.2)\",\n boxShadow: \"0 8px 32px rgba(0, 0, 0, 0.5)\",\n transition: \"all 0.25s ease\"\n },\n onMouseEnter: (e) => {\n const el = e.currentTarget;\n el.style.background = \"rgba(255, 255, 255, 0.15)\";\n el.style.borderColor = \"rgba(255, 255, 255, 0.35)\";\n el.style.transform = \"translate(-50%, -50%) scale(1.08)\";\n },\n onMouseLeave: (e) => {\n const el = e.currentTarget;\n el.style.background = \"rgba(0, 0, 0, 0.55)\";\n el.style.borderColor = \"rgba(255, 255, 255, 0.2)\";\n el.style.transform = \"translate(-50%, -50%) scale(1)\";\n },\n title: \"Play\",\n children: /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(\n import_fa.FaPlay,\n {\n size: Math.max(22, 28 * responsiveScale),\n color: \"white\",\n style: { marginLeft: \"4px\", filter: \"drop-shadow(0 1px 3px rgba(0, 0, 0, 0.5))\" }\n }\n )\n }\n ),\n adStatus.showAds && /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)(\n \"div\",\n {\n style: {\n position: \"absolute\",\n top: `${12 * responsiveScale}px`,\n left: `${12 * responsiveScale}px`,\n zIndex: 20,\n display: \"flex\",\n alignItems: \"center\",\n gap: \"8px\",\n animation: \"sc-fade-in 0.3s ease\"\n },\n children: [\n /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(\n \"div\",\n {\n style: {\n background: \"rgba(234, 179, 8, 0.9)\",\n backdropFilter: \"blur(12px)\",\n color: \"#000\",\n padding: `${4 * responsiveScale}px ${12 * responsiveScale}px`,\n borderRadius: \"6px\",\n fontSize: `${11 * responsiveScale}px`,\n fontWeight: \"700\",\n letterSpacing: \"0.08em\",\n textTransform: \"uppercase\",\n boxShadow: \"0 2px 12px rgba(234, 179, 8, 0.3)\"\n },\n children: \"Ad\"\n }\n ),\n adStatus.currentIndex > 0 && /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)(\n \"div\",\n {\n style: {\n background: \"rgba(0, 0, 0, 0.5)\",\n backdropFilter: \"blur(12px)\",\n color: \"rgba(255, 255, 255, 0.8)\",\n padding: `${4 * responsiveScale}px ${10 * responsiveScale}px`,\n borderRadius: \"6px\",\n fontSize: `${11 * responsiveScale}px`,\n fontWeight: \"600\",\n border: \"1px solid rgba(255, 255, 255, 0.08)\"\n },\n children: [\n adStatus.currentIndex,\n \" of \",\n Math.max(adStatus.totalAds, adStatus.currentIndex)\n ]\n }\n ),\n adStatus.remainingSeconds > 0 && /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)(\n \"div\",\n {\n style: {\n background: \"rgba(0, 0, 0, 0.5)\",\n backdropFilter: \"blur(12px)\",\n color: \"rgba(255, 255, 255, 0.9)\",\n padding: `${4 * responsiveScale}px ${10 * responsiveScale}px`,\n borderRadius: \"6px\",\n fontSize: `${11 * responsiveScale}px`,\n fontWeight: \"600\",\n border: \"1px solid rgba(255, 255, 255, 0.08)\"\n },\n children: [\n adStatus.remainingSeconds,\n \"s\"\n ]\n }\n )\n ]\n }\n ),\n showAiPanel && !showLicenseWarning && (swirlProjectId || adcisionChannelId) && /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)(\n \"div\",\n {\n style: {\n position: \"absolute\",\n right: `${panelBaseRight}px`,\n ...shouldStackPanels && showDebugPanel ? { top: `${12 * responsiveScale}px` } : { bottom: `${debugPanelBottomOffset}px` },\n width: `${analyzerPanelWidth}px`,\n maxWidth: \"92vw\",\n height: analyzerPanelHeight,\n maxHeight: analyzerPanelMaxHeight,\n zIndex: 61,\n background: \"linear-gradient(165deg, rgba(17, 24, 39, 0.94) 0%, rgba(41, 17, 63, 0.82) 52%, rgba(17, 24, 39, 0.9) 100%)\",\n border: \"1px solid rgba(236, 72, 153, 0.35)\",\n borderRadius: \"14px\",\n boxShadow: \"0 18px 56px rgba(4, 7, 20, 0.58), inset 0 1px 0 rgba(255, 255, 255, 0.09)\",\n backdropFilter: \"blur(20px)\",\n WebkitBackdropFilter: \"blur(20px)\",\n color: \"rgba(255,255,255,0.96)\",\n overflow: \"hidden\"\n },\n children: [\n /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)(\n \"div\",\n {\n style: {\n display: \"flex\",\n alignItems: \"center\",\n justifyContent: \"space-between\",\n padding: \"11px 13px\",\n borderBottom: \"1px solid rgba(255,255,255,0.12)\",\n background: \"linear-gradient(90deg, rgba(236, 72, 153, 0.2) 0%, rgba(168, 85, 247, 0.18) 100%)\"\n },\n children: [\n /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)(\"div\", { children: [\n /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(\n \"div\",\n {\n style: {\n fontSize: \"13px\",\n fontWeight: 800,\n letterSpacing: \"0.02em\"\n },\n children: \"AI Live Context Analyzer\"\n }\n ),\n /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(\n \"div\",\n {\n style: {\n marginTop: \"2px\",\n fontSize: \"11px\",\n color: \"rgba(255,255,255,0.72)\"\n },\n children: aiLiveContext.lastPolledAt ? `Updated ${formatDebugClock(aiLiveContext.lastPolledAt)}` : \"Waiting for first sample...\"\n }\n )\n ] }),\n /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(\n \"button\",\n {\n className: \"sc-ctrl-btn\",\n onClick: () => setShowAiPanel(false),\n style: {\n padding: \"4px\",\n borderRadius: \"6px\",\n minWidth: \"26px\",\n minHeight: \"26px\"\n },\n title: \"Close AI panel\",\n children: /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(import_fa.FaTimes, { size: 12 })\n }\n )\n ]\n }\n ),\n /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(\n \"div\",\n {\n className: \"sc-ai-scroll\",\n style: {\n padding: \"12px\",\n overflowY: \"auto\",\n overflowX: \"hidden\",\n height: \"calc(100% - 52px)\",\n display: \"grid\",\n gap: \"12px\"\n },\n children: adStatus.inAdBreak ? /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)(\n \"div\",\n {\n style: {\n display: \"flex\",\n flexDirection: \"column\",\n alignItems: \"center\",\n justifyContent: \"center\",\n gap: \"12px\",\n padding: \"24px 12px\",\n borderRadius: \"10px\",\n border: \"1px solid rgba(234, 179, 8, 0.5)\",\n background: \"linear-gradient(155deg, rgba(92, 64, 0, 0.45) 0%, rgba(17, 24, 39, 0.62) 100%)\",\n boxShadow: \"0 8px 24px rgba(234, 179, 8, 0.12)\"\n },\n children: [\n /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(\n \"div\",\n {\n style: {\n width: \"36px\",\n height: \"36px\",\n borderRadius: \"50%\",\n background: \"rgba(234, 179, 8, 0.18)\",\n border: \"2px solid rgba(234, 179, 8, 0.7)\",\n display: \"flex\",\n alignItems: \"center\",\n justifyContent: \"center\",\n fontSize: \"16px\"\n },\n children: \"\\u{1F4FA}\"\n }\n ),\n /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(\n \"div\",\n {\n style: {\n fontSize: \"13px\",\n fontWeight: 700,\n color: \"#fde68a\",\n letterSpacing: \"0.04em\",\n textAlign: \"center\"\n },\n children: \"Now Ad Playing\"\n }\n ),\n /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(\n \"div\",\n {\n style: {\n fontSize: \"11px\",\n color: \"rgba(255,255,255,0.55)\",\n textAlign: \"center\",\n lineHeight: \"1.5\"\n },\n children: \"AI context will resume after the ad break.\"\n }\n )\n ]\n }\n ) : /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)(import_jsx_runtime2.Fragment, { children: [\n aiLiveContext.error && /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(\n \"div\",\n {\n style: {\n fontSize: \"12px\",\n color: \"#fecaca\",\n background: \"rgba(220, 38, 38, 0.2)\",\n border: \"1px solid rgba(248, 113, 113, 0.5)\",\n borderRadius: \"10px\",\n padding: \"9px 10px\"\n },\n children: aiLiveContext.error\n }\n ),\n /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)(\n \"div\",\n {\n style: {\n padding: \"11px 12px\",\n borderRadius: \"10px\",\n border: \"1px solid rgba(236, 72, 153, 0.5)\",\n background: \"linear-gradient(155deg, rgba(88, 28, 135, 0.35) 0%, rgba(17, 24, 39, 0.62) 100%)\",\n boxShadow: \"0 8px 24px rgba(236, 72, 153, 0.12)\"\n },\n children: [\n /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)(\n \"div\",\n {\n style: {\n display: \"flex\",\n alignItems: \"center\",\n justifyContent: \"space-between\",\n gap: \"8px\",\n marginBottom: \"7px\"\n },\n children: [\n /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(\n \"div\",\n {\n style: {\n fontSize: \"11px\",\n fontWeight: 800,\n textTransform: \"uppercase\",\n letterSpacing: \"0.1em\",\n color: \"#f9a8d4\"\n },\n children: \"AI Context\"\n }\n ),\n /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(\n \"div\",\n {\n style: {\n fontSize: \"10px\",\n color: \"rgba(255,255,255,0.72)\",\n fontFamily: \"'SF Mono', 'Cascadia Code', monospace\"\n },\n children: aiLiveContext.context ? formatAiRelativeTime(aiLiveContext.context.updated_at) : \"--\"\n }\n )\n ]\n }\n ),\n /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(\n \"div\",\n {\n style: {\n fontSize: \"13px\",\n lineHeight: \"1.58\",\n color: \"rgba(255,255,255,0.95)\",\n whiteSpace: \"pre-wrap\"\n },\n children: aiLiveContext.context?.context ?? (aiLiveContext.isLoading ? \"Analyzing live stream...\" : \"Waiting for AI context response.\")\n }\n )\n ]\n }\n )\n ] })\n }\n )\n ]\n }\n ),\n debugAdTiming && showDebugPanel && !showLicenseWarning && /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)(\n \"div\",\n {\n style: {\n position: \"absolute\",\n right: `${debugPanelRightOffset}px`,\n bottom: `${debugPanelBottomOffset}px`,\n width: `${analyzerPanelWidth}px`,\n maxWidth: \"92vw\",\n height: analyzerPanelHeight,\n maxHeight: analyzerPanelMaxHeight,\n zIndex: 60,\n background: \"rgba(10, 10, 10, 0.74)\",\n border: \"1px solid rgba(255, 255, 255, 0.14)\",\n borderRadius: \"12px\",\n boxShadow: \"0 16px 48px rgba(0, 0, 0, 0.45)\",\n backdropFilter: \"blur(16px)\",\n WebkitBackdropFilter: \"blur(16px)\",\n color: \"rgba(255,255,255,0.94)\",\n overflow: \"hidden\"\n },\n children: [\n /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)(\n \"div\",\n {\n style: {\n display: \"flex\",\n alignItems: \"center\",\n justifyContent: \"space-between\",\n padding: \"10px 12px\",\n borderBottom: \"1px solid rgba(255,255,255,0.1)\"\n },\n children: [\n /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(\n \"div\",\n {\n style: {\n fontSize: \"13px\",\n fontWeight: 700,\n letterSpacing: \"0.02em\"\n },\n children: \"Ad Insertion Debug\"\n }\n ),\n /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(\n \"button\",\n {\n className: \"sc-ctrl-btn\",\n onClick: () => setShowDebugPanel(false),\n style: {\n padding: \"4px\",\n borderRadius: \"6px\",\n minWidth: \"26px\",\n minHeight: \"26px\"\n },\n title: \"Close panel\",\n children: /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(import_fa.FaTimes, { size: 12 })\n }\n )\n ]\n }\n ),\n /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(\n \"div\",\n {\n className: \"sc-debug-scroll\",\n style: {\n padding: \"10px 12px 12px\",\n overflowY: \"auto\",\n overflowX: \"hidden\",\n height: \"calc(100% - 46px)\",\n display: \"grid\",\n gap: \"12px\",\n minWidth: 0\n },\n children: /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)(\"div\", { style: { minWidth: 0 }, children: [\n /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(\n \"div\",\n {\n style: {\n fontSize: \"11px\",\n fontWeight: 700,\n textTransform: \"uppercase\",\n letterSpacing: \"0.08em\",\n color: \"rgba(255,255,255,0.68)\",\n marginBottom: \"8px\"\n },\n children: \"Ad Insertion Points\"\n }\n ),\n /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(\n \"div\",\n {\n style: {\n display: \"grid\",\n gap: \"6px\",\n minWidth: 0\n },\n children: debugMarkers.length === 0 ? /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(\n \"div\",\n {\n style: {\n fontSize: \"12px\",\n color: \"rgba(255,255,255,0.55)\"\n },\n children: \"No ad insertion events yet.\"\n }\n ) : debugMarkers.map((entry, idx) => {\n const evt = formatAdInsertionEvent(entry.event);\n const fileName = entry.segmentName ? entry.segmentName.split(\"/\").pop() || entry.segmentName : \"\";\n return /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)(\n \"div\",\n {\n style: {\n minWidth: 0,\n fontFamily: \"'SF Mono', 'Cascadia Code', monospace\",\n fontSize: \"11px\",\n background: \"rgba(255,255,255,0.05)\",\n border: \"1px solid rgba(255,255,255,0.08)\",\n borderRadius: \"8px\",\n padding: \"6px 8px\",\n display: \"flex\",\n flexDirection: \"column\",\n gap: \"4px\"\n },\n children: [\n /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)(\n \"div\",\n {\n style: {\n display: \"grid\",\n gridTemplateColumns: \"56px 54px minmax(0, 1fr) 20px\",\n gap: \"6px\",\n alignItems: \"center\",\n minWidth: 0\n },\n children: [\n /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(\"span\", { style: { color: \"rgba(255,255,255,0.68)\" }, children: formatDebugClock(entry.timestampMs) }),\n /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(\n \"span\",\n {\n style: {\n fontWeight: 700,\n color: evt.color,\n fontSize: \"10px\"\n },\n children: evt.label\n }\n ),\n /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(\n \"span\",\n {\n style: {\n color: \"rgba(255,255,255,0.88)\",\n overflow: \"hidden\",\n textOverflow: \"ellipsis\",\n whiteSpace: \"nowrap\",\n minWidth: 0\n },\n title: entry.segmentName,\n children: fileName\n }\n ),\n /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(\n \"button\",\n {\n onClick: () => navigator.clipboard.writeText(entry.segmentName),\n title: entry.segmentName,\n style: {\n background: \"none\",\n border: \"none\",\n cursor: \"pointer\",\n padding: \"2px\",\n color: \"rgba(255,255,255,0.45)\",\n display: \"flex\",\n alignItems: \"center\",\n justifyContent: \"center\",\n borderRadius: \"4px\",\n flexShrink: 0\n },\n onMouseEnter: (e) => e.currentTarget.style.color = \"rgba(255,255,255,0.9)\",\n onMouseLeave: (e) => e.currentTarget.style.color = \"rgba(255,255,255,0.45)\",\n children: /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(import_fa.FaCopy, { size: 10 })\n }\n )\n ]\n }\n ),\n (entry.offsetSeconds != null || entry.detail || entry.updatedAt) && /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)(\n \"div\",\n {\n style: {\n display: \"flex\",\n flexWrap: \"wrap\",\n gap: \"6px\",\n paddingLeft: \"0px\",\n fontSize: \"10px\"\n },\n children: [\n entry.offsetSeconds != null && /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)(\n \"span\",\n {\n style: {\n color: \"rgba(255,255,255,0.55)\",\n background: \"rgba(255,255,255,0.06)\",\n borderRadius: \"4px\",\n padding: \"1px 5px\"\n },\n children: [\n \"+\",\n entry.offsetSeconds.toFixed(2),\n \"s\"\n ]\n }\n ),\n entry.detail && /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(\n \"span\",\n {\n style: {\n color: \"rgba(255,255,255,0.55)\",\n background: \"rgba(255,255,255,0.06)\",\n borderRadius: \"4px\",\n padding: \"1px 5px\",\n overflow: \"hidden\",\n textOverflow: \"ellipsis\",\n whiteSpace: \"nowrap\",\n maxWidth: \"100%\"\n },\n children: entry.detail\n }\n ),\n entry.updatedAt && /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(\n \"span\",\n {\n style: {\n color: \"rgba(255,255,255,0.38)\",\n background: \"rgba(255,255,255,0.04)\",\n borderRadius: \"4px\",\n padding: \"1px 5px\"\n },\n children: formatAiRelativeTime(entry.updatedAt)\n }\n )\n ]\n }\n )\n ]\n },\n `${entry.timestampMs}-${idx}`\n );\n })\n }\n )\n ] })\n }\n )\n ]\n }\n ),\n shouldShowEnhancedControls && !showLicenseWarning ? /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)(\n \"div\",\n {\n className: \"sc-controls-bar\",\n style: {\n position: \"absolute\",\n bottom: 0,\n left: 0,\n right: 0,\n background: \"linear-gradient(0deg, rgba(0, 0, 0, 0.8) 0%, rgba(0, 0, 0, 0.35) 60%, transparent 100%)\",\n padding: `${20 * responsiveScale}px ${12 * responsiveScale}px ${8 * responsiveScale}px`,\n zIndex: 10,\n opacity: controlsVisible || adStatus.showAds ? 1 : 0,\n transform: controlsVisible || adStatus.showAds ? \"translateY(0)\" : \"translateY(6px)\",\n pointerEvents: controlsVisible || adStatus.showAds ? \"auto\" : \"none\"\n },\n children: [\n /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)(\n \"div\",\n {\n className: \"sc-progress-track\",\n style: {\n width: \"100%\",\n height: \"3px\",\n background: \"rgba(255, 255, 255, 0.2)\",\n borderRadius: \"1.5px\",\n marginBottom: `${8 * responsiveScale}px`,\n cursor: \"pointer\",\n position: \"relative\",\n transition: \"height 0.1s ease\"\n },\n onClick: handleTimelineSeek,\n onMouseEnter: (e) => {\n e.currentTarget.style.height = \"5px\";\n },\n onMouseLeave: (e) => {\n e.currentTarget.style.height = \"3px\";\n },\n children: [\n /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(\n \"div\",\n {\n style: {\n position: \"absolute\",\n top: 0,\n left: 0,\n bottom: 0,\n background: adStatus.showAds ? \"#f5c518\" : \"#ff0000\",\n borderRadius: \"1.5px\",\n width: `${progressPercent}%`,\n transition: \"width 0.15s linear\"\n }\n }\n ),\n /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(\n \"div\",\n {\n className: \"sc-progress-thumb\",\n style: {\n position: \"absolute\",\n top: \"50%\",\n left: `${progressPercent}%`,\n transform: \"translate(-50%, -50%) scale(0)\",\n width: \"13px\",\n height: \"13px\",\n background: adStatus.showAds ? \"#f5c518\" : \"#ff0000\",\n borderRadius: \"50%\",\n boxShadow: \"0 0 4px rgba(0, 0, 0, 0.3)\",\n transition: \"transform 0.1s ease, left 0.15s linear\"\n }\n }\n )\n ]\n }\n ),\n /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)(\n \"div\",\n {\n style: {\n display: \"flex\",\n alignItems: \"center\",\n justifyContent: \"space-between\",\n color: \"white\",\n gap: `${8 * responsiveScale}px`\n },\n children: [\n /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)(\n \"div\",\n {\n style: {\n display: \"flex\",\n alignItems: \"center\",\n gap: `${8 * responsiveScale}px`\n },\n children: [\n /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(\n \"button\",\n {\n className: \"sc-ctrl-btn\",\n onClick: handlePlayPause,\n style: {\n padding: `${8 * responsiveScale}px`,\n borderRadius: \"50%\",\n minWidth: `${36 * responsiveScale}px`,\n minHeight: `${36 * responsiveScale}px`\n },\n title: isPlaying ? \"Pause\" : \"Play\",\n children: isPlaying ? /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(import_fa.FaPause, { size: Math.max(14, 18 * responsiveScale) }) : /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(import_fa.FaPlay, { size: Math.max(14, 18 * responsiveScale), style: { marginLeft: \"2px\" } })\n }\n ),\n /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)(\n \"div\",\n {\n style: {\n display: \"flex\",\n alignItems: \"center\",\n paddingRight: `${6 * responsiveScale}px`\n },\n onMouseEnter: () => setShowVolumeSlider(true),\n onMouseLeave: () => setShowVolumeSlider(false),\n children: [\n /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(\n \"button\",\n {\n className: \"sc-ctrl-btn\",\n onClick: () => {\n if (playerRef.current) {\n playerRef.current.toggleMute();\n }\n onVolumeToggle?.();\n resetControlsTimer();\n },\n style: {\n padding: `${8 * responsiveScale}px`,\n borderRadius: \"50%\",\n minWidth: `${36 * responsiveScale}px`,\n minHeight: `${36 * responsiveScale}px`\n },\n title: isMuted ? \"Unmute\" : \"Mute\",\n children: /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(VolumeIcon, { size: Math.max(14, 18 * responsiveScale) })\n }\n ),\n /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(\n \"div\",\n {\n style: {\n width: showVolumeSlider ? `${68 * responsiveScale}px` : \"0px\",\n overflow: \"hidden\",\n transition: \"width 0.2s cubic-bezier(0.4, 0, 0.2, 1)\",\n display: \"flex\",\n alignItems: \"center\",\n paddingLeft: showVolumeSlider ? `${3 * responsiveScale}px` : \"0\",\n paddingRight: showVolumeSlider ? `${8 * responsiveScale}px` : \"0\"\n },\n children: /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)(\n \"div\",\n {\n style: {\n position: \"relative\",\n width: `${56 * responsiveScale}px`,\n height: \"3px\",\n cursor: \"pointer\",\n borderRadius: \"1.5px\"\n },\n onMouseDown: (e) => {\n e.preventDefault();\n const el = e.currentTarget;\n const move = (ev) => {\n const r2 = el.getBoundingClientRect();\n handleVolumeChange(Math.max(0, Math.min(1, (ev.clientX - r2.left) / r2.width)));\n };\n const up = () => {\n document.removeEventListener(\"mousemove\", move);\n document.removeEventListener(\"mouseup\", up);\n };\n document.addEventListener(\"mousemove\", move);\n document.addEventListener(\"mouseup\", up);\n const r = el.getBoundingClientRect();\n handleVolumeChange(Math.max(0, Math.min(1, (e.clientX - r.left) / r.width)));\n },\n onClick: (e) => {\n e.stopPropagation();\n const r = e.currentTarget.getBoundingClientRect();\n handleVolumeChange(Math.max(0, Math.min(1, (e.clientX - r.left) / r.width)));\n },\n children: [\n /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(\"div\", { style: { position: \"absolute\", inset: 0, background: \"rgba(255, 255, 255, 0.2)\", borderRadius: \"1.5px\" } }),\n /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(\n \"div\",\n {\n style: {\n position: \"absolute\",\n top: 0,\n left: 0,\n bottom: 0,\n width: `${(isMuted ? 0 : volume) * 100}%`,\n background: \"#fff\",\n borderRadius: \"1.5px\",\n transition: \"width 0.1s ease-out\"\n }\n }\n ),\n /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(\n \"div\",\n {\n style: {\n position: \"absolute\",\n top: \"50%\",\n left: `${(isMuted ? 0 : volume) * 100}%`,\n transform: \"translate(-50%, -50%)\",\n width: \"12px\",\n height: \"12px\",\n background: \"#fff\",\n borderRadius: \"50%\",\n boxShadow: \"0 0 3px rgba(0, 0, 0, 0.3)\",\n transition: \"left 0.1s ease-out\"\n }\n }\n )\n ]\n }\n )\n }\n )\n ]\n }\n ),\n /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)(\n \"div\",\n {\n style: {\n fontSize: `${13 * responsiveScale}px`,\n fontFamily: \"Roboto, 'Segoe UI', Arial, sans-serif\",\n color: \"rgba(255, 255, 255, 0.9)\",\n display: viewportWidth < 480 ? \"none\" : \"block\",\n fontVariantNumeric: \"tabular-nums\",\n userSelect: \"none\",\n marginLeft: `${4 * responsiveScale}px`\n },\n children: [\n formatTime(currentTime),\n \" \",\n /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(\"span\", { style: { color: \"rgba(255,255,255,0.5)\" }, children: \"/\" }),\n \" \",\n formatTime(duration)\n ]\n }\n )\n ]\n }\n ),\n /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)(\n \"div\",\n {\n style: {\n display: \"flex\",\n alignItems: \"center\",\n gap: `${8 * responsiveScale}px`\n },\n children: [\n (showAdsControl ?? true) && /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(\n \"button\",\n {\n className: \"sc-ctrl-btn\",\n onClick: () => {\n const next = !adsDisabled;\n setAdsDisabled(next);\n playerRef.current?.setDisableAds(next);\n resetControlsTimer();\n },\n style: {\n padding: `${8 * responsiveScale}px`,\n borderRadius: \"50%\",\n minWidth: `${36 * responsiveScale}px`,\n minHeight: `${36 * responsiveScale}px`,\n background: adsDisabled ? \"rgba(239, 68, 68, 0.28)\" : \"transparent\",\n fontFamily: \"'SF Mono', 'Cascadia Code', monospace\",\n fontSize: `${12 * responsiveScale}px`,\n fontWeight: 700,\n letterSpacing: \"0.03em\",\n color: adsDisabled ? \"rgba(252, 165, 165, 0.9)\" : \"rgba(255, 255, 255, 0.75)\",\n textDecoration: adsDisabled ? \"line-through\" : \"none\"\n },\n title: adsDisabled ? \"Enable ads\" : \"Disable ads\",\n children: \"AD\"\n }\n ),\n swirlProjectId && (showOverlaysControl ?? true) && /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(\n \"button\",\n {\n className: \"sc-ctrl-btn\",\n onClick: () => {\n setOverlaysDisabled((prev) => !prev);\n resetControlsTimer();\n },\n style: {\n padding: `${8 * responsiveScale}px`,\n borderRadius: \"50%\",\n minWidth: `${36 * responsiveScale}px`,\n minHeight: `${36 * responsiveScale}px`,\n background: overlaysDisabled ? \"rgba(239, 68, 68, 0.28)\" : \"transparent\",\n color: overlaysDisabled ? \"rgba(252, 165, 165, 0.9)\" : \"rgba(255, 255, 255, 0.75)\",\n opacity: overlaysDisabled ? 1 : 0.9\n },\n title: overlaysDisabled ? \"Enable overlays\" : \"Disable overlays\",\n children: /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(import_fa.FaLayerGroup, { size: Math.max(14, 18 * responsiveScale) })\n }\n ),\n (swirlProjectId || adcisionChannelId) && (showAiContextControl ?? true) && /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(\n \"button\",\n {\n className: \"sc-ctrl-btn\",\n onClick: () => {\n setShowAiPanel((prev) => !prev);\n resetControlsTimer();\n },\n style: {\n padding: `${8 * responsiveScale}px`,\n borderRadius: \"50%\",\n minWidth: `${36 * responsiveScale}px`,\n minHeight: `${36 * responsiveScale}px`,\n background: showAiPanel ? \"rgba(236, 72, 153, 0.34)\" : \"transparent\",\n fontFamily: \"'SF Mono', 'Cascadia Code', monospace\",\n fontSize: `${12 * responsiveScale}px`,\n fontWeight: 700,\n letterSpacing: \"0.03em\"\n },\n title: showAiPanel ? \"Hide AI context\" : \"Show AI context\",\n children: \"AI\"\n }\n ),\n (showDebugControl ?? true) && /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(\n \"button\",\n {\n className: \"sc-ctrl-btn\",\n onClick: () => {\n setShowDebugPanel((prev) => !prev);\n resetControlsTimer();\n },\n style: {\n padding: `${8 * responsiveScale}px`,\n borderRadius: \"50%\",\n minWidth: `${36 * responsiveScale}px`,\n minHeight: `${36 * responsiveScale}px`,\n background: showDebugPanel ? \"rgba(255, 255, 255, 0.16)\" : \"transparent\"\n },\n title: showDebugPanel ? \"Hide debug panel\" : \"Show debug panel\",\n children: /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(import_fa.FaCog, { size: Math.max(14, 18 * responsiveScale) })\n }\n ),\n /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)(\"div\", { style: { position: \"relative\", display: viewportWidth < 600 ? \"none\" : \"block\" }, children: [\n /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)(\n \"button\",\n {\n className: \"sc-ctrl-btn\",\n onClick: () => {\n setShowSpeedMenu(!showSpeedMenu);\n resetControlsTimer();\n },\n style: {\n padding: `${6 * responsiveScale}px ${10 * responsiveScale}px`,\n borderRadius: `${6 * responsiveScale}px`,\n fontSize: `${13 * responsiveScale}px`,\n fontFamily: \"'SF Mono', 'Cascadia Code', monospace\",\n fontWeight: \"600\",\n minHeight: `${32 * responsiveScale}px`\n },\n title: \"Playback Speed\",\n children: [\n playbackRate,\n \"x\"\n ]\n }\n ),\n showSpeedMenu && /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(\n \"div\",\n {\n style: {\n position: \"absolute\",\n bottom: \"100%\",\n right: 0,\n marginBottom: \"8px\",\n background: \"rgba(0, 0, 0, 0.8)\",\n backdropFilter: \"blur(24px)\",\n WebkitBackdropFilter: \"blur(24px)\",\n borderRadius: \"10px\",\n border: \"1px solid rgba(255, 255, 255, 0.1)\",\n overflow: \"hidden\",\n minWidth: \"80px\",\n boxShadow: \"0 12px 40px rgba(0, 0, 0, 0.5)\",\n animation: \"sc-fade-in 0.15s ease\"\n },\n children: [0.25, 0.5, 0.75, 1, 1.25, 1.5, 1.75, 2].map((speed) => /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)(\n \"button\",\n {\n onClick: () => handlePlaybackRateChange(speed),\n style: {\n display: \"block\",\n width: \"100%\",\n padding: `${8 * responsiveScale}px ${14 * responsiveScale}px`,\n background: playbackRate === speed ? \"rgba(255, 255, 255, 0.12)\" : \"transparent\",\n border: \"none\",\n color: playbackRate === speed ? \"#fff\" : \"rgba(255, 255, 255, 0.7)\",\n cursor: \"pointer\",\n fontSize: `${12 * responsiveScale}px`,\n fontFamily: \"'SF Mono', monospace\",\n fontWeight: playbackRate === speed ? \"700\" : \"500\",\n textAlign: \"center\",\n transition: \"background 0.15s ease, color 0.15s ease\"\n },\n onMouseEnter: (e) => {\n if (playbackRate !== speed) {\n e.target.style.background = \"rgba(255, 255, 255, 0.08)\";\n e.target.style.color = \"#fff\";\n }\n },\n onMouseLeave: (e) => {\n if (playbackRate !== speed) {\n e.target.style.background = \"transparent\";\n e.target.style.color = \"rgba(255, 255, 255, 0.7)\";\n }\n },\n children: [\n speed,\n \"x\"\n ]\n },\n speed\n ))\n }\n )\n ] }),\n /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(\n \"button\",\n {\n className: \"sc-ctrl-btn\",\n onClick: () => {\n if (onFullscreenToggle) {\n onFullscreenToggle();\n } else if (wrapperRef.current) {\n if (!document.fullscreenElement) {\n wrapperRef.current.requestFullscreen().catch(() => {\n });\n } else {\n document.exitFullscreen().catch(() => {\n });\n }\n }\n resetControlsTimer();\n },\n style: {\n padding: `${8 * responsiveScale}px`,\n borderRadius: \"50%\",\n minWidth: `${36 * responsiveScale}px`,\n minHeight: `${36 * responsiveScale}px`\n },\n title: isFullscreen ? \"Exit Fullscreen\" : \"Enter Fullscreen\",\n children: isFullscreen ? /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(import_fa.FaCompress, { size: Math.max(14, 18 * responsiveScale) }) : /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(import_fa.FaExpand, { size: Math.max(14, 18 * responsiveScale) })\n }\n )\n ]\n }\n )\n ]\n }\n )\n ]\n }\n ) : showCustomControls && !showLicenseWarning && /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)(\n \"div\",\n {\n className: \"sc-controls-bar\",\n style: {\n position: \"absolute\",\n bottom: `${10 * responsiveScale}px`,\n right: `${10 * responsiveScale}px`,\n display: \"flex\",\n flexDirection: isPortrait ? \"column\" : \"row\",\n gap: `${8 * responsiveScale}px`,\n zIndex: 10,\n opacity: controlsVisible ? 1 : 0,\n transform: controlsVisible ? \"translateY(0)\" : \"translateY(4px)\",\n pointerEvents: controlsVisible ? \"auto\" : \"none\"\n },\n children: [\n /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)(\n \"div\",\n {\n style: {\n display: \"flex\",\n alignItems: \"center\",\n background: \"rgba(0, 0, 0, 0.6)\",\n borderRadius: `${18 * responsiveScale}px`,\n padding: \"2px\",\n paddingRight: `${8 * responsiveScale}px`\n },\n onMouseEnter: () => setShowVolumeSlider(true),\n onMouseLeave: () => setShowVolumeSlider(false),\n children: [\n /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(\n \"button\",\n {\n className: \"sc-ctrl-btn\",\n onClick: () => {\n if (playerRef.current) playerRef.current.toggleMute();\n onVolumeToggle?.();\n resetControlsTimer();\n },\n style: {\n padding: `${8 * responsiveScale}px`,\n borderRadius: \"50%\",\n minWidth: `${36 * responsiveScale}px`,\n minHeight: `${36 * responsiveScale}px`\n },\n title: isMuted ? \"Unmute\" : \"Mute\",\n children: /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(VolumeIcon, { size: Math.max(14, 18 * responsiveScale) })\n }\n ),\n /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(\n \"div\",\n {\n style: {\n width: showVolumeSlider ? `${68 * responsiveScale}px` : \"0px\",\n overflow: \"hidden\",\n transition: \"width 0.2s cubic-bezier(0.4, 0, 0.2, 1)\",\n display: \"flex\",\n alignItems: \"center\",\n paddingLeft: showVolumeSlider ? `${3 * responsiveScale}px` : \"0\",\n paddingRight: showVolumeSlider ? `${10 * responsiveScale}px` : \"0\"\n },\n children: /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)(\n \"div\",\n {\n style: {\n position: \"relative\",\n width: `${56 * responsiveScale}px`,\n height: \"3px\",\n cursor: \"pointer\",\n borderRadius: \"1.5px\"\n },\n onMouseDown: (e) => {\n e.preventDefault();\n const el = e.currentTarget;\n const move = (ev) => {\n const r2 = el.getBoundingClientRect();\n handleVolumeChange(Math.max(0, Math.min(1, (ev.clientX - r2.left) / r2.width)));\n };\n const up = () => {\n document.removeEventListener(\"mousemove\", move);\n document.removeEventListener(\"mouseup\", up);\n };\n document.addEventListener(\"mousemove\", move);\n document.addEventListener(\"mouseup\", up);\n const r = el.getBoundingClientRect();\n handleVolumeChange(Math.max(0, Math.min(1, (e.clientX - r.left) / r.width)));\n },\n onClick: (e) => {\n e.stopPropagation();\n const r = e.currentTarget.getBoundingClientRect();\n handleVolumeChange(Math.max(0, Math.min(1, (e.clientX - r.left) / r.width)));\n },\n children: [\n /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(\"div\", { style: { position: \"absolute\", inset: 0, background: \"rgba(255, 255, 255, 0.2)\", borderRadius: \"1.5px\" } }),\n /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(\n \"div\",\n {\n style: {\n position: \"absolute\",\n top: 0,\n left: 0,\n bottom: 0,\n width: `${(isMuted ? 0 : volume) * 100}%`,\n background: \"#fff\",\n borderRadius: \"1.5px\",\n transition: \"width 0.1s ease-out\"\n }\n }\n ),\n /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(\n \"div\",\n {\n style: {\n position: \"absolute\",\n top: \"50%\",\n left: `${(isMuted ? 0 : volume) * 100}%`,\n transform: \"translate(-50%, -50%)\",\n width: \"12px\",\n height: \"12px\",\n background: \"#fff\",\n borderRadius: \"50%\",\n boxShadow: \"0 0 3px rgba(0, 0, 0, 0.3)\",\n transition: \"left 0.1s ease-out\"\n }\n }\n )\n ]\n }\n )\n }\n )\n ]\n }\n ),\n (showAdsControl ?? true) && /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(\n \"button\",\n {\n className: \"sc-ctrl-btn\",\n onClick: () => {\n const next = !adsDisabled;\n setAdsDisabled(next);\n playerRef.current?.setDisableAds(next);\n resetControlsTimer();\n },\n style: {\n padding: `${8 * responsiveScale}px`,\n borderRadius: \"50%\",\n minWidth: `${36 * responsiveScale}px`,\n minHeight: `${36 * responsiveScale}px`,\n background: adsDisabled ? \"rgba(239, 68, 68, 0.28)\" : \"rgba(0, 0, 0, 0.6)\",\n fontFamily: \"'SF Mono', 'Cascadia Code', monospace\",\n fontSize: `${12 * responsiveScale}px`,\n fontWeight: 700,\n letterSpacing: \"0.03em\",\n color: adsDisabled ? \"rgba(252, 165, 165, 0.9)\" : \"rgba(255, 255, 255, 0.75)\",\n textDecoration: adsDisabled ? \"line-through\" : \"none\"\n },\n title: adsDisabled ? \"Enable ads\" : \"Disable ads\",\n children: \"AD\"\n }\n ),\n swirlProjectId && (showOverlaysControl ?? true) && /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(\n \"button\",\n {\n className: \"sc-ctrl-btn\",\n onClick: () => {\n setOverlaysDisabled((prev) => !prev);\n resetControlsTimer();\n },\n style: {\n padding: `${8 * responsiveScale}px`,\n borderRadius: \"50%\",\n minWidth: `${36 * responsiveScale}px`,\n minHeight: `${36 * responsiveScale}px`,\n background: overlaysDisabled ? \"rgba(239, 68, 68, 0.28)\" : \"rgba(0, 0, 0, 0.6)\",\n color: overlaysDisabled ? \"rgba(252, 165, 165, 0.9)\" : \"rgba(255, 255, 255, 0.75)\"\n },\n title: overlaysDisabled ? \"Enable overlays\" : \"Disable overlays\",\n children: /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(import_fa.FaLayerGroup, { size: Math.max(14, 18 * responsiveScale) })\n }\n ),\n (swirlProjectId || adcisionChannelId) && (showAiContextControl ?? true) && /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(\n \"button\",\n {\n className: \"sc-ctrl-btn\",\n onClick: () => {\n setShowAiPanel((prev) => !prev);\n resetControlsTimer();\n },\n style: {\n padding: `${8 * responsiveScale}px`,\n borderRadius: \"50%\",\n minWidth: `${36 * responsiveScale}px`,\n minHeight: `${36 * responsiveScale}px`,\n background: showAiPanel ? \"rgba(236, 72, 153, 0.34)\" : \"rgba(0, 0, 0, 0.6)\",\n fontFamily: \"'SF Mono', 'Cascadia Code', monospace\",\n fontSize: `${12 * responsiveScale}px`,\n fontWeight: 700,\n letterSpacing: \"0.03em\"\n },\n title: showAiPanel ? \"Hide AI context\" : \"Show AI context\",\n children: \"AI\"\n }\n ),\n (showDebugControl ?? true) && /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(\n \"button\",\n {\n className: \"sc-ctrl-btn\",\n onClick: () => {\n setShowDebugPanel((prev) => !prev);\n resetControlsTimer();\n },\n style: {\n padding: `${8 * responsiveScale}px`,\n borderRadius: \"50%\",\n minWidth: `${36 * responsiveScale}px`,\n minHeight: `${36 * responsiveScale}px`,\n background: showDebugPanel ? \"rgba(255, 255, 255, 0.16)\" : \"rgba(0, 0, 0, 0.6)\"\n },\n title: showDebugPanel ? \"Hide debug panel\" : \"Show debug panel\",\n children: /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(import_fa.FaCog, { size: Math.max(14, 18 * responsiveScale) })\n }\n ),\n /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(\n \"button\",\n {\n className: \"sc-ctrl-btn\",\n onClick: () => {\n if (onFullscreenToggle) {\n onFullscreenToggle();\n } else if (wrapperRef.current) {\n if (!document.fullscreenElement) {\n wrapperRef.current.requestFullscreen().catch(() => {\n });\n } else {\n document.exitFullscreen().catch(() => {\n });\n }\n }\n resetControlsTimer();\n },\n style: {\n padding: `${8 * responsiveScale}px`,\n borderRadius: \"50%\",\n minWidth: `${36 * responsiveScale}px`,\n minHeight: `${36 * responsiveScale}px`,\n background: \"rgba(0, 0, 0, 0.6)\"\n },\n title: isFullscreen ? \"Exit Fullscreen\" : \"Enter Fullscreen\",\n children: isFullscreen ? /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(import_fa.FaCompress, { size: Math.max(14, 18 * responsiveScale) }) : /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(import_fa.FaExpand, { size: Math.max(14, 18 * responsiveScale) })\n }\n )\n ]\n }\n ),\n onControlClick && /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(\n \"div\",\n {\n onClick: onControlClick,\n style: {\n position: \"absolute\",\n top: 0,\n left: 0,\n right: 0,\n bottom: 0,\n zIndex: 1,\n cursor: \"pointer\"\n }\n }\n )\n ]\n }\n )\n ] });\n },\n (prevProps, nextProps) => {\n for (const prop of CRITICAL_PROPS) {\n if (prevProps[prop] !== nextProps[prop]) {\n return false;\n }\n }\n const uiProps = [\n \"autoplay\",\n \"muted\",\n \"controls\",\n \"showCustomControls\",\n \"className\",\n \"style\",\n \"wrapperClassName\",\n \"wrapperStyle\",\n \"playsInline\",\n \"preload\",\n \"poster\",\n \"children\",\n \"swirlProjectId\",\n \"swirlShowcaseDemo\",\n \"swirlOverlayApiBaseUrl\",\n \"swirlOverlayCoordinateSpace\",\n \"adcisionChannelId\",\n \"disableOverlays\",\n \"showAdsControl\",\n \"showOverlaysControl\",\n \"showAiContextControl\",\n \"showDebugControl\"\n ];\n for (const prop of uiProps) {\n if (prevProps[prop] !== nextProps[prop]) {\n return false;\n }\n }\n const callbackProps = [\n \"onReady\",\n \"onVolumeToggle\",\n \"onFullscreenToggle\",\n \"onControlClick\"\n ];\n for (const prop of callbackProps) {\n if (prevProps[prop] !== nextProps[prop]) {\n return false;\n }\n }\n return true;\n }\n);\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n StormcloudVideoPlayerComponent\n});\n","import React, { useEffect, useRef, useMemo, useCallback, useState } from \"react\";\nimport { StormcloudVideoPlayer } from \"../player/StormcloudVideoPlayer\";\nimport type { StormcloudVideoPlayerConfig } from \"../types\";\nimport {\n FaPlay,\n FaPause,\n FaVolumeUp,\n FaVolumeMute,\n FaVolumeDown,\n FaExpand,\n FaCompress,\n FaCog,\n FaTimes,\n FaCopy,\n FaLayerGroup,\n} from \"react-icons/fa\";\nimport { OverlayRenderer } from \"./OverlayRenderer\";\nimport {\n fetchProjectOverlays,\n OVERLAY_API_BASE,\n type SwirlOverlay,\n type OverlayCoordinateSpace,\n} from \"../utils/overlays\";\nimport { fetchAdcisionChannel, fetchAdcisionChannelLiveContext } from \"../utils/adcision\";\n\nexport type StormcloudVideoPlayerProps = Omit<\n StormcloudVideoPlayerConfig,\n \"videoElement\"\n> &\n React.VideoHTMLAttributes<HTMLVideoElement> & {\n onReady?: (player: StormcloudVideoPlayer) => void;\n wrapperClassName?: string;\n wrapperStyle?: React.CSSProperties;\n licenseKey?: string;\n swirlProjectId?: number;\n swirlShowcaseDemo?: boolean;\n swirlOverlayApiBaseUrl?: string;\n swirlOverlayCoordinateSpace?: { width: number; height: number } | null;\n adcisionChannelId?: number;\n disableOverlays?: boolean;\n showAdsControl?: boolean;\n showOverlaysControl?: boolean;\n showAiContextControl?: boolean;\n showDebugControl?: boolean;\n };\n\nconst CRITICAL_PROPS = [\n \"src\",\n \"allowNativeHls\",\n \"licenseKey\",\n \"lowLatencyMode\",\n \"driftToleranceMs\",\n \"debugAdTiming\",\n] as const;\n\nconst CONTROLS_HIDE_DELAY = 3000;\nconst DEFAULT_PLAYER_ASPECT_RATIO = 16 / 9;\nconst DEBUG_PANEL_MARKER_LIMIT = 12;\nconst AI_CONTEXT_FALLBACK_POLL_MS = 4000;\nconst AI_CONTEXT_MIN_POLL_MS = 800;\nconst PANEL_BASE_RIGHT_OFFSET = 10;\n\ninterface LiveContextPayload {\n id: number;\n project_id: number;\n keywords: string[];\n context: string;\n updated_at: string;\n}\n\nexport const StormcloudVideoPlayerComponent: React.FC<StormcloudVideoPlayerProps> =\n React.memo(\n (props) => {\n const {\n src,\n autoplay,\n muted,\n lowLatencyMode,\n allowNativeHls,\n driftToleranceMs,\n immediateManifestAds,\n debugAdTiming,\n showCustomControls,\n hideLoadingIndicator,\n onVolumeToggle,\n onFullscreenToggle,\n onControlClick,\n onReady,\n wrapperClassName,\n wrapperStyle,\n className,\n style,\n controls,\n playsInline,\n preload,\n poster,\n children,\n licenseKey,\n minSegmentsBeforePlay,\n disableAds,\n disableFiller,\n swirlProjectId,\n swirlShowcaseDemo,\n swirlOverlayApiBaseUrl,\n swirlOverlayCoordinateSpace,\n adcisionChannelId,\n disableOverlays,\n showAdsControl,\n showOverlaysControl,\n showAiContextControl,\n showDebugControl,\n ...restVideoAttrs\n } = props;\n\n const [adcisionSrc, setAdcisionSrc] = useState<string | null>(null);\n\n const videoRef = useRef<HTMLVideoElement | null>(null);\n const playerRef = useRef<StormcloudVideoPlayer | null>(null);\n const bufferingTimeoutRef = useRef<number | null>(null);\n const controlsTimerRef = useRef<number | null>(null);\n const wrapperRef = useRef<HTMLDivElement | null>(null);\n\n const [adStatus, setAdStatus] = React.useState<{\n showAds: boolean;\n inAdBreak: boolean;\n currentIndex: number;\n totalAds: number;\n remainingSeconds: number;\n }>({ showAds: false, inAdBreak: false, currentIndex: 0, totalAds: 0, remainingSeconds: 0 });\n\n const [shouldShowNativeControls, setShouldShowNativeControls] =\n React.useState(true);\n\n const [isMuted, setIsMuted] = React.useState(false);\n const [isFullscreen, setIsFullscreen] = React.useState(false);\n const [isPlaying, setIsPlaying] = React.useState(false);\n const [currentTime, setCurrentTime] = React.useState(0);\n const [duration, setDuration] = React.useState(0);\n const [volume, setVolume] = React.useState(1);\n const [playbackRate, setPlaybackRate] = React.useState(1);\n const [showVolumeSlider, setShowVolumeSlider] = React.useState(false);\n const [showSpeedMenu, setShowSpeedMenu] = React.useState(false);\n const [isLoading, setIsLoading] = React.useState(true);\n const [isBuffering, setIsBuffering] = React.useState(false);\n const [showCenterPlay, setShowCenterPlay] = React.useState(false);\n const [showLicenseWarning, setShowLicenseWarning] = React.useState(false);\n const [controlsVisible, setControlsVisible] = React.useState(true);\n const [overlays, setOverlays] = React.useState<SwirlOverlay[]>([]);\n\n const overlayApiBase = React.useMemo(\n () => swirlOverlayApiBaseUrl?.replace(/\\/$/, \"\") || OVERLAY_API_BASE,\n [swirlOverlayApiBaseUrl]\n );\n\n const [overlayCoordSpace, setOverlayCoordSpace] =\n React.useState<OverlayCoordinateSpace | null>(null);\n\n const displayOverlays = overlays;\n const [viewportWidth, setViewportWidth] = React.useState(\n typeof window !== \"undefined\" ? window.innerWidth : 1920\n );\n const [isPortrait, setIsPortrait] = React.useState(\n typeof window !== \"undefined\"\n ? window.innerHeight > window.innerWidth\n : false\n );\n const [playerAspectRatio, setPlayerAspectRatio] = React.useState(\n DEFAULT_PLAYER_ASPECT_RATIO\n );\n const [showDebugPanel, setShowDebugPanel] = React.useState(false);\n const [debugMarkers, setDebugMarkers] = React.useState<\n ReadonlyArray<{\n timestampMs: number;\n event: string;\n segmentName: string;\n offsetSeconds?: number;\n updatedAt?: string;\n detail?: string;\n }>\n >([]);\n const [showAiPanel, setShowAiPanel] = React.useState(false);\n const [adsDisabled, setAdsDisabled] = React.useState(disableAds ?? false);\n const [overlaysDisabled, setOverlaysDisabled] = React.useState(disableOverlays ?? false);\n const [aiLiveContext, setAiLiveContext] = React.useState<{\n context: LiveContextPayload | null;\n isLoading: boolean;\n error: string | null;\n lastPolledAt: number | null;\n }>({\n context: null,\n isLoading: false,\n error: null,\n lastPolledAt: null,\n });\n\n const getResponsiveScale = () => {\n if (viewportWidth < 480) return 0.7;\n if (viewportWidth < 768) return 0.8;\n if (viewportWidth < 1024) return 0.9;\n return 1;\n };\n\n const responsiveScale = getResponsiveScale();\n\n const formatDebugClock = (timestampMs: number): string => {\n try {\n const localTimeZone = Intl.DateTimeFormat().resolvedOptions().timeZone;\n return new Date(timestampMs).toLocaleTimeString(\"en-GB\", {\n hour12: false,\n hour: \"2-digit\",\n minute: \"2-digit\",\n second: \"2-digit\",\n timeZone: localTimeZone,\n });\n } catch {\n return \"--:--:--\";\n }\n };\n\n const formatAdInsertionEvent = (event: string): { label: string; color: string } => {\n switch (event) {\n case \"api_response\":\n return { label: \"API\", color: \"#60a5fa\" };\n case \"scte35_inserted\":\n return { label: \"SCTE-35\", color: \"#f43f5e\" };\n case \"segment_found\":\n return { label: \"FOUND\", color: \"#a78bfa\" };\n case \"segment_playing\":\n return { label: \"PLAYING\", color: \"#fbbf24\" };\n case \"ad_scheduled\":\n return { label: \"SCHED\", color: \"#fb923c\" };\n case \"ad_triggered\":\n return { label: \"TRIGGER\", color: \"#34d399\" };\n default:\n return { label: event, color: \"rgba(255,255,255,0.68)\" };\n }\n };\n\n const formatAiRelativeTime = (timestamp: string): string => {\n const epochMs = Date.parse(timestamp);\n if (!Number.isFinite(epochMs)) return \"unknown\";\n const diffSec = Math.max(0, Math.floor((Date.now() - epochMs) / 1000));\n if (diffSec < 5) return \"just now\";\n if (diffSec < 60) return `${diffSec}s ago`;\n const diffMin = Math.floor(diffSec / 60);\n if (diffMin < 60) return `${diffMin}m ago`;\n const diffHr = Math.floor(diffMin / 60);\n if (diffHr < 24) return `${diffHr}h ago`;\n return `${Math.floor(diffHr / 24)}d ago`;\n };\n\n const resetControlsTimer = useCallback(() => {\n if (controlsTimerRef.current) {\n clearTimeout(controlsTimerRef.current);\n }\n setControlsVisible(true);\n controlsTimerRef.current = window.setTimeout(() => {\n if (!showVolumeSlider && !showSpeedMenu) {\n setControlsVisible(false);\n }\n }, CONTROLS_HIDE_DELAY);\n }, [showVolumeSlider, showSpeedMenu]);\n\n const formatTime = (seconds: number): string => {\n if (!isFinite(seconds)) return \"0:00:00\";\n const hours = Math.floor(seconds / 3600);\n const minutes = Math.floor((seconds % 3600) / 60);\n const remainingSeconds = Math.floor(seconds % 60);\n return `${hours}:${minutes\n .toString()\n .padStart(2, \"0\")}:${remainingSeconds.toString().padStart(2, \"0\")}`;\n };\n\n const handlePlayPause = () => {\n if (videoRef.current) {\n if (videoRef.current.paused) {\n const hasValidSource =\n videoRef.current.src ||\n (videoRef.current.currentSrc &&\n videoRef.current.currentSrc !== \"\") ||\n videoRef.current.readyState >= 1;\n\n if (hasValidSource) {\n videoRef.current.play()?.catch((error) => {\n console.error(\"[StormcloudVideoPlayer] Failed to play:\", error);\n });\n setShowCenterPlay(false);\n }\n } else {\n videoRef.current.pause();\n setShowCenterPlay(true);\n }\n }\n resetControlsTimer();\n };\n\n const handleCenterPlayClick = () => {\n if (videoRef.current && videoRef.current.paused) {\n const hasValidSource =\n videoRef.current.src ||\n (videoRef.current.currentSrc &&\n videoRef.current.currentSrc !== \"\") ||\n videoRef.current.readyState >= 1;\n\n if (hasValidSource) {\n videoRef.current.play()?.catch((error) => {\n console.error(\"[StormcloudVideoPlayer] Failed to play:\", error);\n });\n setShowCenterPlay(false);\n }\n }\n };\n\n const handleTimelineSeek = (e: React.MouseEvent<HTMLDivElement>) => {\n if (videoRef.current && duration > 0 && isFinite(duration)) {\n const rect = e.currentTarget.getBoundingClientRect();\n const clickX = e.clientX - rect.left;\n const progress = Math.max(0, Math.min(1, clickX / rect.width));\n const newTime = progress * duration;\n\n if (isFinite(newTime) && newTime >= 0 && newTime <= duration) {\n videoRef.current.currentTime = newTime;\n }\n }\n resetControlsTimer();\n };\n\n const handleVolumeChange = (newVolume: number) => {\n if (playerRef.current && isFinite(newVolume)) {\n const clampedVolume = Math.max(0, Math.min(1, newVolume));\n playerRef.current.setVolume(clampedVolume);\n }\n };\n\n const handlePlaybackRateChange = (rate: number) => {\n if (videoRef.current && isFinite(rate) && rate > 0) {\n videoRef.current.playbackRate = rate;\n }\n setShowSpeedMenu(false);\n };\n\n const analyzerPanelWidth = Math.min(420, Math.max(320, viewportWidth * 0.41));\n const analyzerPanelHeight = isPortrait ? \"52vh\" : \"420px\";\n const analyzerPanelMaxHeight = \"60vh\";\n const panelGap = Math.max(8, 12 * responsiveScale);\n const shouldStackPanels = isPortrait || viewportWidth < 980;\n const panelBaseRight = PANEL_BASE_RIGHT_OFFSET * responsiveScale;\n const debugPanelRightOffset =\n showAiPanel && !shouldStackPanels\n ? panelBaseRight + analyzerPanelWidth + panelGap\n : panelBaseRight;\n\n useEffect(() => {\n if (!adcisionChannelId) {\n setAdcisionSrc(null);\n return;\n }\n let cancelled = false;\n fetchAdcisionChannel(adcisionChannelId)\n .then((ch) => {\n if (!cancelled) setAdcisionSrc(ch.stream_url);\n })\n .catch((err) => {\n if (!cancelled) {\n console.warn(\"[StormcloudVideoPlayer] Failed to fetch adcision channel:\", err);\n }\n });\n return () => {\n cancelled = true;\n };\n }, [adcisionChannelId]);\n\n const effectiveSrc = adcisionChannelId ? adcisionSrc : src;\n\n const isHlsStream =\n effectiveSrc?.toLowerCase().includes(\".m3u8\") ||\n effectiveSrc?.toLowerCase().includes(\"/hls/\");\n const shouldShowEnhancedControls =\n showCustomControls && (isHlsStream ? allowNativeHls : true);\n const debugPanelBottomOffset = shouldShowEnhancedControls\n ? Math.max(74, 92 * responsiveScale)\n : Math.max(52, 58 * responsiveScale);\n\n const criticalPropsKey = useMemo(() => {\n const baseParts = CRITICAL_PROPS.map((prop) =>\n prop === \"src\" ? `src:${effectiveSrc}` : `${prop}:${props[prop]}`\n ).join(\"|\");\n return `${baseParts}|adcisionChannelId:${adcisionChannelId ?? \"\"}`;\n }, [\n effectiveSrc,\n allowNativeHls,\n licenseKey,\n lowLatencyMode,\n driftToleranceMs,\n adcisionChannelId,\n debugAdTiming,\n ]);\n\n useEffect(() => {\n if (typeof window === \"undefined\") return;\n const el = videoRef.current;\n if (!el || !effectiveSrc) return;\n\n if (!licenseKey) {\n setShowLicenseWarning(true);\n setIsLoading(false);\n return;\n }\n\n setShowLicenseWarning(false);\n\n if (playerRef.current) {\n try {\n playerRef.current.destroy();\n } catch {}\n playerRef.current = null;\n }\n\n const cfg: StormcloudVideoPlayerConfig = {\n src: effectiveSrc,\n videoElement: el,\n } as StormcloudVideoPlayerConfig;\n if (autoplay !== undefined) cfg.autoplay = autoplay;\n if (muted !== undefined) cfg.muted = muted;\n if (lowLatencyMode !== undefined) cfg.lowLatencyMode = lowLatencyMode;\n if (allowNativeHls !== undefined) cfg.allowNativeHls = allowNativeHls;\n if (driftToleranceMs !== undefined)\n cfg.driftToleranceMs = driftToleranceMs;\n if (immediateManifestAds !== undefined)\n cfg.immediateManifestAds = immediateManifestAds;\n if (debugAdTiming !== undefined) cfg.debugAdTiming = debugAdTiming;\n if (showCustomControls !== undefined)\n cfg.showCustomControls = showCustomControls;\n if (onVolumeToggle !== undefined) cfg.onVolumeToggle = onVolumeToggle;\n if (onFullscreenToggle !== undefined)\n cfg.onFullscreenToggle = onFullscreenToggle;\n if (onControlClick !== undefined) cfg.onControlClick = onControlClick;\n if (licenseKey !== undefined) cfg.licenseKey = licenseKey;\n if (minSegmentsBeforePlay !== undefined)\n cfg.minSegmentsBeforePlay = minSegmentsBeforePlay;\n if (disableAds !== undefined) cfg.disableAds = disableAds;\n cfg.disableFiller = disableFiller ?? true;\n if (adcisionChannelId !== undefined) {\n cfg.projectId = String(adcisionChannelId);\n cfg.channelId = adcisionChannelId;\n } else if (swirlProjectId !== undefined)\n cfg.projectId = String(swirlProjectId);\n\n const player = new StormcloudVideoPlayer(cfg);\n playerRef.current = player;\n player\n .load()\n .then(() => {\n const showNative = player.shouldShowNativeControls();\n setShouldShowNativeControls(showNative);\n onReady?.(player);\n })\n .catch((error) => {\n console.error(\n \"StormcloudVideoPlayer: Failed to load player:\",\n error\n );\n setIsLoading(false);\n onReady?.(player);\n });\n\n return () => {\n try {\n player.destroy();\n } catch {}\n playerRef.current = null;\n };\n }, [criticalPropsKey]);\n\n useEffect(() => {\n if (!swirlProjectId || adcisionChannelId) {\n setOverlays([]);\n setOverlayCoordSpace(null);\n return;\n }\n let cancelled = false;\n const loadOverlays = () => {\n fetchProjectOverlays(swirlProjectId, overlayApiBase)\n .then((data) => {\n if (!cancelled) setOverlays(data);\n })\n .catch((err) => {\n if (!cancelled) {\n console.warn(\"[StormcloudVideoPlayer] Failed to fetch overlays:\", err);\n }\n });\n };\n loadOverlays();\n const interval = window.setInterval(loadOverlays, 25000);\n return () => {\n cancelled = true;\n clearInterval(interval);\n };\n }, [swirlProjectId, adcisionChannelId, overlayApiBase]);\n\n useEffect(() => {\n if (!swirlProjectId) return;\n\n const tryResolve = (): boolean => {\n const fixed = swirlOverlayCoordinateSpace;\n if (fixed && fixed.width > 0 && fixed.height > 0) {\n console.debug(\n \"[StormcloudVideoPlayer] overlay coord space (prop):\",\n fixed.width,\n \"x\",\n fixed.height\n );\n setOverlayCoordSpace({ width: fixed.width, height: fixed.height });\n return true;\n }\n const player = playerRef.current;\n if (!player) return false;\n\n const minRes = player.getMinHlsResolution?.();\n if (minRes && minRes.width > 0 && minRes.height > 0) {\n console.debug(\n \"[StormcloudVideoPlayer] overlay coord space (minHlsResolution):\",\n minRes.width,\n \"x\",\n minRes.height\n );\n setOverlayCoordSpace({ width: minRes.width, height: minRes.height });\n return true;\n }\n\n const video = player.videoElement;\n if (video && video.videoWidth > 0 && video.videoHeight > 0) {\n console.debug(\n \"[StormcloudVideoPlayer] overlay coord space (videoNative):\",\n video.videoWidth,\n \"x\",\n video.videoHeight\n );\n setOverlayCoordSpace({\n width: video.videoWidth,\n height: video.videoHeight,\n });\n return true;\n }\n return false;\n };\n\n let attempts = 0;\n const maxAttempts = 40;\n tryResolve();\n\n const interval = setInterval(() => {\n attempts++;\n if (!swirlOverlayCoordinateSpace) {\n tryResolve();\n }\n if (attempts >= maxAttempts) clearInterval(interval);\n }, 300);\n\n const onVideoDims = () => {\n if (!swirlOverlayCoordinateSpace) {\n tryResolve();\n }\n };\n\n const video = playerRef.current?.videoElement;\n video?.addEventListener(\"loadedmetadata\", onVideoDims);\n\n return () => {\n clearInterval(interval);\n video?.removeEventListener(\"loadedmetadata\", onVideoDims);\n };\n }, [swirlProjectId, criticalPropsKey, swirlOverlayCoordinateSpace]);\n\n useEffect(() => {\n if (!playerRef.current) return;\n try {\n if (autoplay !== undefined && playerRef.current.videoElement) {\n playerRef.current.videoElement.autoplay = autoplay;\n }\n if (muted !== undefined && !playerRef.current.isShowingAds()) {\n playerRef.current.setMuted(muted);\n }\n } catch (error) {\n console.warn(\"Failed to update player properties:\", error);\n }\n }, [autoplay, muted]);\n\n useEffect(() => {\n if (!playerRef.current) return;\n\n const checkAdStatus = () => {\n if (playerRef.current) {\n const showAdsFromMethod = playerRef.current.isShowingAds();\n const showAdsFromAttribute = videoRef.current?.dataset?.stormcloudAdPlaying === \"true\";\n const showAds = showAdsFromMethod || showAdsFromAttribute;\n const inAdBreak = playerRef.current.isInAdBreak?.() ?? showAds;\n const currentIndex = playerRef.current.getCurrentAdIndex();\n const totalAds = playerRef.current.getTotalAdsInBreak();\n const remainingSeconds = playerRef.current.getRemainingAdSeconds();\n\n setAdStatus((prev) => {\n if (\n prev.showAds !== showAds ||\n prev.inAdBreak !== inAdBreak ||\n prev.currentIndex !== currentIndex ||\n prev.totalAds !== totalAds ||\n prev.remainingSeconds !== remainingSeconds\n ) {\n if (showAds && !prev.showAds) {\n setShowCenterPlay(false);\n }\n return {\n showAds,\n inAdBreak,\n currentIndex,\n totalAds,\n remainingSeconds,\n };\n }\n return prev;\n });\n }\n };\n\n const interval = setInterval(checkAdStatus, 50);\n return () => clearInterval(interval);\n }, []);\n\n useEffect(() => {\n if (typeof window === \"undefined\" || !playerRef.current) return;\n\n const handleResize = () => {\n if (playerRef.current && videoRef.current) {\n if (typeof playerRef.current.resize === \"function\") {\n playerRef.current.resize();\n }\n }\n setViewportWidth(window.innerWidth);\n setIsPortrait(window.innerHeight > window.innerWidth);\n };\n\n window.addEventListener(\"resize\", handleResize);\n return () => window.removeEventListener(\"resize\", handleResize);\n }, []);\n\n useEffect(() => {\n if (!playerRef.current || !videoRef.current) return;\n\n const updateStates = () => {\n if (playerRef.current && videoRef.current) {\n setIsMuted(playerRef.current.isMuted());\n setIsPlaying(!videoRef.current.paused);\n\n const currentTimeValue = videoRef.current.currentTime;\n setCurrentTime(isFinite(currentTimeValue) ? currentTimeValue : 0);\n\n const durationValue = videoRef.current.duration;\n setDuration(isFinite(durationValue) ? durationValue : 0);\n\n const volumeValue = playerRef.current.getVolume();\n setVolume(\n isFinite(volumeValue) ? Math.max(0, Math.min(1, volumeValue)) : 1\n );\n\n const rateValue = videoRef.current.playbackRate;\n setPlaybackRate(\n isFinite(rateValue) && rateValue > 0 ? rateValue : 1\n );\n }\n setIsFullscreen(\n document.fullscreenElement === wrapperRef.current\n );\n };\n\n const interval = setInterval(updateStates, 200);\n\n const handleFullscreenChange = () => {\n setIsFullscreen(\n document.fullscreenElement === wrapperRef.current\n );\n };\n\n document.addEventListener(\"fullscreenchange\", handleFullscreenChange);\n\n return () => {\n clearInterval(interval);\n document.removeEventListener(\n \"fullscreenchange\",\n handleFullscreenChange\n );\n };\n }, []);\n\n useEffect(() => {\n if (!videoRef.current) return;\n\n const handleLoadedMetadata = () => {\n const video = videoRef.current;\n if (!video) return;\n if (video.videoWidth > 0 && video.videoHeight > 0) {\n setPlayerAspectRatio(video.videoWidth / video.videoHeight);\n }\n };\n\n const handleCanPlay = () => {\n setIsLoading(false);\n if (bufferingTimeoutRef.current) {\n clearTimeout(bufferingTimeoutRef.current);\n bufferingTimeoutRef.current = null;\n }\n setIsBuffering(false);\n };\n\n const handleCanPlayThrough = () => {\n setIsLoading(false);\n if (bufferingTimeoutRef.current) {\n clearTimeout(bufferingTimeoutRef.current);\n bufferingTimeoutRef.current = null;\n }\n setIsBuffering(false);\n };\n\n const handleWaiting = () => {\n if (bufferingTimeoutRef.current) {\n clearTimeout(bufferingTimeoutRef.current);\n }\n bufferingTimeoutRef.current = window.setTimeout(() => {\n setIsBuffering(true);\n }, 300);\n };\n\n const handlePlaying = () => {\n setIsLoading(false);\n if (bufferingTimeoutRef.current) {\n clearTimeout(bufferingTimeoutRef.current);\n bufferingTimeoutRef.current = null;\n }\n setIsBuffering(false);\n setShowCenterPlay(false);\n };\n\n const handlePause = () => {\n const isAdActive = playerRef.current?.isShowingAds() ||\n videoRef.current?.dataset?.stormcloudAdPlaying === \"true\";\n if (playerRef.current && !isAdActive) {\n setShowCenterPlay(true);\n } else {\n setShowCenterPlay(false);\n }\n };\n\n const handleEnded = () => {\n setShowCenterPlay(true);\n };\n\n const video = videoRef.current;\n handleLoadedMetadata();\n video.addEventListener(\"loadedmetadata\", handleLoadedMetadata);\n video.addEventListener(\"canplay\", handleCanPlay);\n video.addEventListener(\"canplaythrough\", handleCanPlayThrough);\n video.addEventListener(\"waiting\", handleWaiting);\n video.addEventListener(\"playing\", handlePlaying);\n video.addEventListener(\"pause\", handlePause);\n video.addEventListener(\"ended\", handleEnded);\n\n if (video.paused) {\n setShowCenterPlay(true);\n }\n\n return () => {\n if (bufferingTimeoutRef.current) {\n clearTimeout(bufferingTimeoutRef.current);\n bufferingTimeoutRef.current = null;\n }\n video.removeEventListener(\"loadedmetadata\", handleLoadedMetadata);\n video.removeEventListener(\"canplay\", handleCanPlay);\n video.removeEventListener(\"canplaythrough\", handleCanPlayThrough);\n video.removeEventListener(\"waiting\", handleWaiting);\n video.removeEventListener(\"playing\", handlePlaying);\n video.removeEventListener(\"pause\", handlePause);\n video.removeEventListener(\"ended\", handleEnded);\n };\n }, [debugAdTiming]);\n\n useEffect(() => {\n setPlayerAspectRatio(DEFAULT_PLAYER_ASPECT_RATIO);\n }, [src]);\n\n useEffect(() => {\n return () => {\n if (controlsTimerRef.current) {\n clearTimeout(controlsTimerRef.current);\n }\n };\n }, []);\n\n useEffect(() => {\n if (!debugAdTiming) {\n setShowDebugPanel(false);\n setDebugMarkers([]);\n return;\n }\n\n const updateDebugData = () => {\n const player = playerRef.current;\n if (!player) return;\n setDebugMarkers(\n player\n .getAdInsertionDebugLog()\n .slice(-DEBUG_PANEL_MARKER_LIMIT)\n .reverse()\n );\n };\n\n updateDebugData();\n const interval = window.setInterval(updateDebugData, 500);\n return () => clearInterval(interval);\n }, [debugAdTiming, criticalPropsKey]);\n\n useEffect(() => {\n if (!swirlProjectId || adcisionChannelId) {\n setShowAiPanel(false);\n setAiLiveContext({\n context: null,\n isLoading: false,\n error: null,\n lastPolledAt: null,\n });\n }\n }, [swirlProjectId, adcisionChannelId]);\n\n useEffect(() => {\n if (!showAiPanel || (!swirlProjectId && !adcisionChannelId)) return;\n\n let cancelled = false;\n let pollTimeoutId: number | null = null;\n let inFlight = false;\n\n const pollLiveContext = async () => {\n if (cancelled || inFlight) return;\n inFlight = true;\n setAiLiveContext((prev) => ({\n ...prev,\n isLoading: prev.context == null,\n error: null,\n }));\n\n try {\n let payload: LiveContextPayload;\n if (adcisionChannelId) {\n const adcisionCtx = await fetchAdcisionChannelLiveContext(adcisionChannelId);\n payload = {\n id: adcisionCtx.id,\n project_id: adcisionCtx.channel_id,\n keywords: adcisionCtx.keywords,\n context: adcisionCtx.context,\n updated_at: adcisionCtx.updated_at,\n };\n } else {\n const response = await fetch(\n `https://adstorm.co/api-adstorm-dev/adstorm/swirl/projects/${swirlProjectId}/live-context`,\n {\n method: \"GET\",\n headers: {\n Accept: \"application/json\",\n },\n }\n );\n if (!response.ok) {\n throw new Error(\n `Live context request failed (${response.status} ${response.statusText})`\n );\n }\n payload = (await response.json()) as LiveContextPayload;\n }\n if (cancelled) return;\n\n setAiLiveContext({\n context: payload,\n isLoading: false,\n error: null,\n lastPolledAt: Date.now(),\n });\n } catch (error) {\n if (cancelled) return;\n const message =\n error instanceof Error\n ? error.message\n : \"Unable to load AI live context.\";\n setAiLiveContext((prev) => ({\n ...prev,\n isLoading: false,\n error: message,\n lastPolledAt: Date.now(),\n }));\n } finally {\n inFlight = false;\n if (!cancelled) {\n const segmentPollMs =\n playerRef.current?.getCurrentHlsSegmentDurationMs() ??\n AI_CONTEXT_FALLBACK_POLL_MS;\n const nextPollMs = Math.max(AI_CONTEXT_MIN_POLL_MS, segmentPollMs);\n pollTimeoutId = window.setTimeout(pollLiveContext, nextPollMs);\n }\n }\n };\n\n pollLiveContext();\n\n return () => {\n cancelled = true;\n if (pollTimeoutId != null) {\n clearTimeout(pollTimeoutId);\n }\n };\n }, [showAiPanel, swirlProjectId, adcisionChannelId, criticalPropsKey]);\n\n const handleWrapperMouseMove = useCallback(() => {\n resetControlsTimer();\n }, [resetControlsTimer]);\n\n const handleWrapperMouseLeave = useCallback(() => {\n if (!showVolumeSlider && !showSpeedMenu) {\n setControlsVisible(false);\n }\n }, [showVolumeSlider, showSpeedMenu]);\n\n const progressPercent = duration > 0 ? (currentTime / duration) * 100 : 0;\n\n const VolumeIcon = isMuted || volume === 0\n ? FaVolumeMute\n : volume < 0.5\n ? FaVolumeDown\n : FaVolumeUp;\n\n return (\n <>\n <style>\n {`\n @keyframes sc-spin {\n from { transform: rotate(0deg); }\n to { transform: rotate(360deg); }\n }\n @keyframes sc-loading-glow {\n 0%, 100% { opacity: 0.85; transform: scale(1); }\n 50% { opacity: 1; transform: scale(1.05); }\n }\n @keyframes sc-pulse {\n 0%, 100% { opacity: 1; }\n 50% { opacity: 0.6; }\n }\n @keyframes sc-fade-in {\n from { opacity: 0; transform: translateY(8px); }\n to { opacity: 1; transform: translateY(0); }\n }\n .sc-wrapper:fullscreen,\n .sc-wrapper:has(*:fullscreen) {\n border-radius: 0 !important;\n box-shadow: none !important;\n width: 100vw !important;\n height: 100vh !important;\n max-width: 100vw !important;\n max-height: 100vh !important;\n position: fixed !important;\n top: 0 !important;\n left: 0 !important;\n z-index: 999999 !important;\n background: #000 !important;\n display: flex !important;\n align-items: center !important;\n justify-content: center !important;\n }\n .sc-ctrl-btn {\n background: none;\n border: none;\n color: #fff;\n cursor: pointer;\n display: flex;\n align-items: center;\n justify-content: center;\n border-radius: 50%;\n padding: 8px;\n transition: background 0.15s ease, opacity 0.15s ease;\n opacity: 0.9;\n }\n .sc-ctrl-btn:hover {\n opacity: 1;\n background: rgba(255, 255, 255, 0.1);\n }\n .sc-ctrl-btn:active {\n opacity: 0.7;\n }\n .sc-controls-bar {\n transition: opacity 0.35s ease, transform 0.35s ease;\n }\n .sc-progress-track:hover .sc-progress-thumb {\n transform: translate(-50%, -50%) scale(1) !important;\n }\n .sc-loading-hidden .sc-loading-indicator {\n display: none !important;\n }\n .sc-debug-scroll::-webkit-scrollbar {\n width: 8px;\n }\n .sc-debug-scroll::-webkit-scrollbar-thumb {\n background: rgba(255, 255, 255, 0.22);\n border-radius: 4px;\n }\n .sc-debug-scroll {\n overflow-x: hidden !important;\n }\n .sc-ai-scroll::-webkit-scrollbar {\n width: 8px;\n }\n .sc-ai-scroll::-webkit-scrollbar-thumb {\n background: rgba(236, 72, 153, 0.34);\n border-radius: 4px;\n }\n .sc-ai-scroll {\n overflow-x: hidden !important;\n }\n `}\n </style>\n <div\n ref={wrapperRef}\n className={`sc-wrapper ${wrapperClassName || \"\"}`}\n onMouseMove={handleWrapperMouseMove}\n onMouseLeave={handleWrapperMouseLeave}\n style={{\n display: \"flex\",\n alignItems: \"center\",\n justifyContent: \"center\",\n position: isFullscreen ? \"fixed\" : \"relative\",\n top: isFullscreen ? 0 : undefined,\n left: isFullscreen ? 0 : undefined,\n overflow: \"hidden\",\n width: isFullscreen ? \"100vw\" : \"100%\",\n height: isFullscreen ? \"100vh\" : \"auto\",\n minHeight: isFullscreen ? \"100vh\" : \"auto\",\n aspectRatio: isFullscreen ? undefined : playerAspectRatio,\n maxWidth: isFullscreen ? \"100vw\" : \"100%\",\n maxHeight: isFullscreen ? \"100vh\" : \"none\",\n zIndex: isFullscreen ? 999999 : undefined,\n backgroundColor: \"#000\",\n borderRadius: isFullscreen ? 0 : undefined,\n boxShadow: isFullscreen ? \"none\" : undefined,\n ...wrapperStyle,\n }}\n >\n <video\n ref={videoRef}\n className={className}\n style={{\n position: \"relative\",\n zIndex: 1,\n display: \"block\",\n width: \"100%\",\n height: \"100%\",\n maxWidth: \"100%\",\n maxHeight: isFullscreen ? \"100%\" : \"none\",\n objectFit: isFullscreen ? \"cover\" : \"contain\",\n backgroundColor: \"#000\",\n aspectRatio: isFullscreen ? \"unset\" : undefined,\n ...style,\n }}\n controls={\n shouldShowNativeControls && controls && !showCustomControls\n }\n playsInline={playsInline}\n preload={preload}\n poster={poster}\n {...restVideoAttrs}\n >\n {children}\n </video>\n\n {displayOverlays.length > 0 &&\n !adStatus.showAds &&\n !overlaysDisabled &&\n overlayCoordSpace && (\n <OverlayRenderer\n overlays={displayOverlays}\n currentTime={currentTime}\n videoRef={videoRef}\n coordinateSpace={overlayCoordSpace}\n showcaseMode={!!swirlShowcaseDemo}\n />\n )}\n\n {(isLoading || isBuffering) && !hideLoadingIndicator && (\n <div\n className=\"sc-loading-indicator\"\n style={{\n position: \"absolute\",\n top: \"50%\",\n left: \"50%\",\n transform: \"translate(-50%, -50%)\",\n zIndex: 20,\n width: `${Math.max(34, 38 * responsiveScale)}px`,\n height: `${Math.max(34, 38 * responsiveScale)}px`,\n display: \"flex\",\n alignItems: \"center\",\n justifyContent: \"center\",\n animation: \"sc-loading-glow 1.4s ease-in-out infinite\",\n filter: \"drop-shadow(0 6px 14px rgba(0, 0, 0, 0.55))\",\n }}\n >\n <div\n style={{\n position: \"absolute\",\n inset: 0,\n borderRadius: \"50%\",\n border: \"3px solid rgba(255, 255, 255, 0.25)\",\n borderTopColor: \"#ff0000\",\n borderRightColor: \"rgba(255, 255, 255, 0.85)\",\n animation: \"sc-spin 0.8s linear infinite\",\n }}\n />\n <div\n style={{\n width: \"7px\",\n height: \"7px\",\n borderRadius: \"50%\",\n background: \"#ff0000\",\n boxShadow: \"0 0 10px rgba(255, 0, 0, 0.65)\",\n }}\n />\n </div>\n )}\n\n {/* License Warning */}\n {showLicenseWarning && (\n <div\n style={{\n position: \"absolute\",\n top: \"50%\",\n left: \"50%\",\n transform: \"translate(-50%, -50%)\",\n zIndex: 25,\n background: \"rgba(220, 38, 38, 0.92)\",\n backdropFilter: \"blur(24px)\",\n color: \"white\",\n padding: \"28px 36px\",\n borderRadius: \"14px\",\n border: \"1px solid rgba(255, 255, 255, 0.15)\",\n boxShadow: \"0 24px 64px rgba(0, 0, 0, 0.5)\",\n textAlign: \"center\",\n maxWidth: \"400px\",\n margin: \"0 16px\",\n }}\n >\n <div style={{ fontSize: \"18px\", fontWeight: \"700\", marginBottom: \"10px\", letterSpacing: \"-0.02em\" }}>\n License Key Required\n </div>\n <div style={{ fontSize: \"13px\", lineHeight: \"1.6\", color: \"rgba(255, 255, 255, 0.85)\" }}>\n Please provide a valid license key to use the Stormcloud Video Player.\n <br />\n Contact your administrator for licensing information.\n </div>\n </div>\n )}\n\n {/* Center Play Button */}\n {showCenterPlay && !isLoading && !isBuffering && !showLicenseWarning && !adStatus.showAds && (\n <div\n onClick={handleCenterPlayClick}\n style={{\n position: \"absolute\",\n top: \"50%\",\n left: \"50%\",\n transform: \"translate(-50%, -50%)\",\n zIndex: 15,\n cursor: \"pointer\",\n background: \"rgba(0, 0, 0, 0.55)\",\n backdropFilter: \"blur(20px)\",\n WebkitBackdropFilter: \"blur(20px)\",\n borderRadius: \"50%\",\n width: `${Math.max(64, 80 * responsiveScale)}px`,\n height: `${Math.max(64, 80 * responsiveScale)}px`,\n display: \"flex\",\n alignItems: \"center\",\n justifyContent: \"center\",\n border: \"1.5px solid rgba(255, 255, 255, 0.2)\",\n boxShadow: \"0 8px 32px rgba(0, 0, 0, 0.5)\",\n transition: \"all 0.25s ease\",\n }}\n onMouseEnter={(e) => {\n const el = e.currentTarget;\n el.style.background = \"rgba(255, 255, 255, 0.15)\";\n el.style.borderColor = \"rgba(255, 255, 255, 0.35)\";\n el.style.transform = \"translate(-50%, -50%) scale(1.08)\";\n }}\n onMouseLeave={(e) => {\n const el = e.currentTarget;\n el.style.background = \"rgba(0, 0, 0, 0.55)\";\n el.style.borderColor = \"rgba(255, 255, 255, 0.2)\";\n el.style.transform = \"translate(-50%, -50%) scale(1)\";\n }}\n title=\"Play\"\n >\n <FaPlay\n size={Math.max(22, 28 * responsiveScale)}\n color=\"white\"\n style={{ marginLeft: \"4px\", filter: \"drop-shadow(0 1px 3px rgba(0, 0, 0, 0.5))\" }}\n />\n </div>\n )}\n\n {/* Ad Badge */}\n {adStatus.showAds && (\n <div\n style={{\n position: \"absolute\",\n top: `${12 * responsiveScale}px`,\n left: `${12 * responsiveScale}px`,\n zIndex: 20,\n display: \"flex\",\n alignItems: \"center\",\n gap: \"8px\",\n animation: \"sc-fade-in 0.3s ease\",\n }}\n >\n <div\n style={{\n background: \"rgba(234, 179, 8, 0.9)\",\n backdropFilter: \"blur(12px)\",\n color: \"#000\",\n padding: `${4 * responsiveScale}px ${12 * responsiveScale}px`,\n borderRadius: \"6px\",\n fontSize: `${11 * responsiveScale}px`,\n fontWeight: \"700\",\n letterSpacing: \"0.08em\",\n textTransform: \"uppercase\" as const,\n boxShadow: \"0 2px 12px rgba(234, 179, 8, 0.3)\",\n }}\n >\n Ad\n </div>\n {adStatus.currentIndex > 0 && (\n <div\n style={{\n background: \"rgba(0, 0, 0, 0.5)\",\n backdropFilter: \"blur(12px)\",\n color: \"rgba(255, 255, 255, 0.8)\",\n padding: `${4 * responsiveScale}px ${10 * responsiveScale}px`,\n borderRadius: \"6px\",\n fontSize: `${11 * responsiveScale}px`,\n fontWeight: \"600\",\n border: \"1px solid rgba(255, 255, 255, 0.08)\",\n }}\n >\n {adStatus.currentIndex} of {Math.max(adStatus.totalAds, adStatus.currentIndex)}\n </div>\n )}\n {adStatus.remainingSeconds > 0 && (\n <div\n style={{\n background: \"rgba(0, 0, 0, 0.5)\",\n backdropFilter: \"blur(12px)\",\n color: \"rgba(255, 255, 255, 0.9)\",\n padding: `${4 * responsiveScale}px ${10 * responsiveScale}px`,\n borderRadius: \"6px\",\n fontSize: `${11 * responsiveScale}px`,\n fontWeight: \"600\",\n border: \"1px solid rgba(255, 255, 255, 0.08)\",\n }}\n >\n {adStatus.remainingSeconds}s\n </div>\n )}\n </div>\n )}\n\n {showAiPanel && !showLicenseWarning && (swirlProjectId || adcisionChannelId) && (\n <div\n style={{\n position: \"absolute\",\n right: `${panelBaseRight}px`,\n ...(shouldStackPanels && showDebugPanel\n ? { top: `${12 * responsiveScale}px` }\n : { bottom: `${debugPanelBottomOffset}px` }),\n width: `${analyzerPanelWidth}px`,\n maxWidth: \"92vw\",\n height: analyzerPanelHeight,\n maxHeight: analyzerPanelMaxHeight,\n zIndex: 61,\n background:\n \"linear-gradient(165deg, rgba(17, 24, 39, 0.94) 0%, rgba(41, 17, 63, 0.82) 52%, rgba(17, 24, 39, 0.9) 100%)\",\n border: \"1px solid rgba(236, 72, 153, 0.35)\",\n borderRadius: \"14px\",\n boxShadow:\n \"0 18px 56px rgba(4, 7, 20, 0.58), inset 0 1px 0 rgba(255, 255, 255, 0.09)\",\n backdropFilter: \"blur(20px)\",\n WebkitBackdropFilter: \"blur(20px)\",\n color: \"rgba(255,255,255,0.96)\",\n overflow: \"hidden\",\n }}\n >\n <div\n style={{\n display: \"flex\",\n alignItems: \"center\",\n justifyContent: \"space-between\",\n padding: \"11px 13px\",\n borderBottom: \"1px solid rgba(255,255,255,0.12)\",\n background:\n \"linear-gradient(90deg, rgba(236, 72, 153, 0.2) 0%, rgba(168, 85, 247, 0.18) 100%)\",\n }}\n >\n <div>\n <div\n style={{\n fontSize: \"13px\",\n fontWeight: 800,\n letterSpacing: \"0.02em\",\n }}\n >\n AI Live Context Analyzer\n </div>\n <div\n style={{\n marginTop: \"2px\",\n fontSize: \"11px\",\n color: \"rgba(255,255,255,0.72)\",\n }}\n >\n {aiLiveContext.lastPolledAt\n ? `Updated ${formatDebugClock(aiLiveContext.lastPolledAt)}`\n : \"Waiting for first sample...\"}\n </div>\n </div>\n <button\n className=\"sc-ctrl-btn\"\n onClick={() => setShowAiPanel(false)}\n style={{\n padding: \"4px\",\n borderRadius: \"6px\",\n minWidth: \"26px\",\n minHeight: \"26px\",\n }}\n title=\"Close AI panel\"\n >\n <FaTimes size={12} />\n </button>\n </div>\n <div\n className=\"sc-ai-scroll\"\n style={{\n padding: \"12px\",\n overflowY: \"auto\",\n overflowX: \"hidden\",\n height: \"calc(100% - 52px)\",\n display: \"grid\",\n gap: \"12px\",\n }}\n >\n {adStatus.inAdBreak ? (\n <div\n style={{\n display: \"flex\",\n flexDirection: \"column\",\n alignItems: \"center\",\n justifyContent: \"center\",\n gap: \"12px\",\n padding: \"24px 12px\",\n borderRadius: \"10px\",\n border: \"1px solid rgba(234, 179, 8, 0.5)\",\n background:\n \"linear-gradient(155deg, rgba(92, 64, 0, 0.45) 0%, rgba(17, 24, 39, 0.62) 100%)\",\n boxShadow: \"0 8px 24px rgba(234, 179, 8, 0.12)\",\n }}\n >\n <div\n style={{\n width: \"36px\",\n height: \"36px\",\n borderRadius: \"50%\",\n background: \"rgba(234, 179, 8, 0.18)\",\n border: \"2px solid rgba(234, 179, 8, 0.7)\",\n display: \"flex\",\n alignItems: \"center\",\n justifyContent: \"center\",\n fontSize: \"16px\",\n }}\n >\n 📺\n </div>\n <div\n style={{\n fontSize: \"13px\",\n fontWeight: 700,\n color: \"#fde68a\",\n letterSpacing: \"0.04em\",\n textAlign: \"center\",\n }}\n >\n Now Ad Playing\n </div>\n <div\n style={{\n fontSize: \"11px\",\n color: \"rgba(255,255,255,0.55)\",\n textAlign: \"center\",\n lineHeight: \"1.5\",\n }}\n >\n AI context will resume after the ad break.\n </div>\n </div>\n ) : (\n <>\n {aiLiveContext.error && (\n <div\n style={{\n fontSize: \"12px\",\n color: \"#fecaca\",\n background: \"rgba(220, 38, 38, 0.2)\",\n border: \"1px solid rgba(248, 113, 113, 0.5)\",\n borderRadius: \"10px\",\n padding: \"9px 10px\",\n }}\n >\n {aiLiveContext.error}\n </div>\n )}\n\n <div\n style={{\n padding: \"11px 12px\",\n borderRadius: \"10px\",\n border: \"1px solid rgba(236, 72, 153, 0.5)\",\n background:\n \"linear-gradient(155deg, rgba(88, 28, 135, 0.35) 0%, rgba(17, 24, 39, 0.62) 100%)\",\n boxShadow: \"0 8px 24px rgba(236, 72, 153, 0.12)\",\n }}\n >\n <div\n style={{\n display: \"flex\",\n alignItems: \"center\",\n justifyContent: \"space-between\",\n gap: \"8px\",\n marginBottom: \"7px\",\n }}\n >\n <div\n style={{\n fontSize: \"11px\",\n fontWeight: 800,\n textTransform: \"uppercase\",\n letterSpacing: \"0.1em\",\n color: \"#f9a8d4\",\n }}\n >\n AI Context\n </div>\n <div\n style={{\n fontSize: \"10px\",\n color: \"rgba(255,255,255,0.72)\",\n fontFamily: \"'SF Mono', 'Cascadia Code', monospace\",\n }}\n >\n {aiLiveContext.context\n ? formatAiRelativeTime(aiLiveContext.context.updated_at)\n : \"--\"}\n </div>\n </div>\n <div\n style={{\n fontSize: \"13px\",\n lineHeight: \"1.58\",\n color: \"rgba(255,255,255,0.95)\",\n whiteSpace: \"pre-wrap\",\n }}\n >\n {aiLiveContext.context?.context ??\n (aiLiveContext.isLoading\n ? \"Analyzing live stream...\"\n : \"Waiting for AI context response.\")}\n </div>\n </div>\n </>\n )}\n </div>\n </div>\n )}\n\n {debugAdTiming && showDebugPanel && !showLicenseWarning && (\n <div\n style={{\n position: \"absolute\",\n right: `${debugPanelRightOffset}px`,\n bottom: `${debugPanelBottomOffset}px`,\n width: `${analyzerPanelWidth}px`,\n maxWidth: \"92vw\",\n height: analyzerPanelHeight,\n maxHeight: analyzerPanelMaxHeight,\n zIndex: 60,\n background: \"rgba(10, 10, 10, 0.74)\",\n border: \"1px solid rgba(255, 255, 255, 0.14)\",\n borderRadius: \"12px\",\n boxShadow: \"0 16px 48px rgba(0, 0, 0, 0.45)\",\n backdropFilter: \"blur(16px)\",\n WebkitBackdropFilter: \"blur(16px)\",\n color: \"rgba(255,255,255,0.94)\",\n overflow: \"hidden\",\n }}\n >\n <div\n style={{\n display: \"flex\",\n alignItems: \"center\",\n justifyContent: \"space-between\",\n padding: \"10px 12px\",\n borderBottom: \"1px solid rgba(255,255,255,0.1)\",\n }}\n >\n <div\n style={{\n fontSize: \"13px\",\n fontWeight: 700,\n letterSpacing: \"0.02em\",\n }}\n >\n Ad Insertion Debug\n </div>\n <button\n className=\"sc-ctrl-btn\"\n onClick={() => setShowDebugPanel(false)}\n style={{\n padding: \"4px\",\n borderRadius: \"6px\",\n minWidth: \"26px\",\n minHeight: \"26px\",\n }}\n title=\"Close panel\"\n >\n <FaTimes size={12} />\n </button>\n </div>\n <div\n className=\"sc-debug-scroll\"\n style={{\n padding: \"10px 12px 12px\",\n overflowY: \"auto\",\n overflowX: \"hidden\",\n height: \"calc(100% - 46px)\",\n display: \"grid\",\n gap: \"12px\",\n minWidth: 0,\n }}\n >\n <div style={{ minWidth: 0 }}>\n <div\n style={{\n fontSize: \"11px\",\n fontWeight: 700,\n textTransform: \"uppercase\",\n letterSpacing: \"0.08em\",\n color: \"rgba(255,255,255,0.68)\",\n marginBottom: \"8px\",\n }}\n >\n Ad Insertion Points\n </div>\n <div\n style={{\n display: \"grid\",\n gap: \"6px\",\n minWidth: 0,\n }}\n >\n {debugMarkers.length === 0 ? (\n <div\n style={{\n fontSize: \"12px\",\n color: \"rgba(255,255,255,0.55)\",\n }}\n >\n No ad insertion events yet.\n </div>\n ) : (\n debugMarkers.map((entry, idx) => {\n const evt = formatAdInsertionEvent(entry.event);\n const fileName = entry.segmentName\n ? entry.segmentName.split(\"/\").pop() || entry.segmentName\n : \"\";\n return (\n <div\n key={`${entry.timestampMs}-${idx}`}\n style={{\n minWidth: 0,\n fontFamily: \"'SF Mono', 'Cascadia Code', monospace\",\n fontSize: \"11px\",\n background: \"rgba(255,255,255,0.05)\",\n border: \"1px solid rgba(255,255,255,0.08)\",\n borderRadius: \"8px\",\n padding: \"6px 8px\",\n display: \"flex\",\n flexDirection: \"column\",\n gap: \"4px\",\n }}\n >\n <div\n style={{\n display: \"grid\",\n gridTemplateColumns: \"56px 54px minmax(0, 1fr) 20px\",\n gap: \"6px\",\n alignItems: \"center\",\n minWidth: 0,\n }}\n >\n <span style={{ color: \"rgba(255,255,255,0.68)\" }}>\n {formatDebugClock(entry.timestampMs)}\n </span>\n <span\n style={{\n fontWeight: 700,\n color: evt.color,\n fontSize: \"10px\",\n }}\n >\n {evt.label}\n </span>\n <span\n style={{\n color: \"rgba(255,255,255,0.88)\",\n overflow: \"hidden\",\n textOverflow: \"ellipsis\",\n whiteSpace: \"nowrap\",\n minWidth: 0,\n }}\n title={entry.segmentName}\n >\n {fileName}\n </span>\n <button\n onClick={() =>\n navigator.clipboard.writeText(entry.segmentName)\n }\n title={entry.segmentName}\n style={{\n background: \"none\",\n border: \"none\",\n cursor: \"pointer\",\n padding: \"2px\",\n color: \"rgba(255,255,255,0.45)\",\n display: \"flex\",\n alignItems: \"center\",\n justifyContent: \"center\",\n borderRadius: \"4px\",\n flexShrink: 0,\n }}\n onMouseEnter={(e) =>\n ((e.currentTarget as HTMLButtonElement).style.color =\n \"rgba(255,255,255,0.9)\")\n }\n onMouseLeave={(e) =>\n ((e.currentTarget as HTMLButtonElement).style.color =\n \"rgba(255,255,255,0.45)\")\n }\n >\n <FaCopy size={10} />\n </button>\n </div>\n {/* Extra metadata row */}\n {(entry.offsetSeconds != null || entry.detail || entry.updatedAt) && (\n <div\n style={{\n display: \"flex\",\n flexWrap: \"wrap\",\n gap: \"6px\",\n paddingLeft: \"0px\",\n fontSize: \"10px\",\n }}\n >\n {entry.offsetSeconds != null && (\n <span\n style={{\n color: \"rgba(255,255,255,0.55)\",\n background: \"rgba(255,255,255,0.06)\",\n borderRadius: \"4px\",\n padding: \"1px 5px\",\n }}\n >\n +{entry.offsetSeconds.toFixed(2)}s\n </span>\n )}\n {entry.detail && (\n <span\n style={{\n color: \"rgba(255,255,255,0.55)\",\n background: \"rgba(255,255,255,0.06)\",\n borderRadius: \"4px\",\n padding: \"1px 5px\",\n overflow: \"hidden\",\n textOverflow: \"ellipsis\",\n whiteSpace: \"nowrap\",\n maxWidth: \"100%\",\n }}\n >\n {entry.detail}\n </span>\n )}\n {entry.updatedAt && (\n <span\n style={{\n color: \"rgba(255,255,255,0.38)\",\n background: \"rgba(255,255,255,0.04)\",\n borderRadius: \"4px\",\n padding: \"1px 5px\",\n }}\n >\n {formatAiRelativeTime(entry.updatedAt)}\n </span>\n )}\n </div>\n )}\n </div>\n );\n })\n )}\n </div>\n </div>\n </div>\n </div>\n )}\n\n {/* Enhanced Controls Bar */}\n {shouldShowEnhancedControls && !showLicenseWarning ? (\n <div\n className=\"sc-controls-bar\"\n style={{\n position: \"absolute\",\n bottom: 0,\n left: 0,\n right: 0,\n background: \"linear-gradient(0deg, rgba(0, 0, 0, 0.8) 0%, rgba(0, 0, 0, 0.35) 60%, transparent 100%)\",\n padding: `${20 * responsiveScale}px ${12 * responsiveScale}px ${8 * responsiveScale}px`,\n zIndex: 10,\n opacity: controlsVisible || adStatus.showAds ? 1 : 0,\n transform: controlsVisible || adStatus.showAds ? \"translateY(0)\" : \"translateY(6px)\",\n pointerEvents: controlsVisible || adStatus.showAds ? \"auto\" : \"none\",\n }}\n >\n {/* Progress Bar */}\n <div\n className=\"sc-progress-track\"\n style={{\n width: \"100%\",\n height: \"3px\",\n background: \"rgba(255, 255, 255, 0.2)\",\n borderRadius: \"1.5px\",\n marginBottom: `${8 * responsiveScale}px`,\n cursor: \"pointer\",\n position: \"relative\",\n transition: \"height 0.1s ease\",\n }}\n onClick={handleTimelineSeek}\n onMouseEnter={(e) => { e.currentTarget.style.height = \"5px\"; }}\n onMouseLeave={(e) => { e.currentTarget.style.height = \"3px\"; }}\n >\n {/* Progress fill */}\n <div\n style={{\n position: \"absolute\",\n top: 0, left: 0, bottom: 0,\n background: adStatus.showAds ? \"#f5c518\" : \"#ff0000\",\n borderRadius: \"1.5px\",\n width: `${progressPercent}%`,\n transition: \"width 0.15s linear\",\n }}\n />\n {/* Thumb */}\n <div\n className=\"sc-progress-thumb\"\n style={{\n position: \"absolute\",\n top: \"50%\",\n left: `${progressPercent}%`,\n transform: \"translate(-50%, -50%) scale(0)\",\n width: \"13px\",\n height: \"13px\",\n background: adStatus.showAds ? \"#f5c518\" : \"#ff0000\",\n borderRadius: \"50%\",\n boxShadow: \"0 0 4px rgba(0, 0, 0, 0.3)\",\n transition: \"transform 0.1s ease, left 0.15s linear\",\n }}\n />\n </div>\n\n {/* Controls Row */}\n <div\n style={{\n display: \"flex\",\n alignItems: \"center\",\n justifyContent: \"space-between\",\n color: \"white\",\n gap: `${8 * responsiveScale}px`,\n }}\n >\n {/* Left Group */}\n <div\n style={{\n display: \"flex\",\n alignItems: \"center\",\n gap: `${8 * responsiveScale}px`,\n }}\n >\n {/* Play/Pause */}\n <button\n className=\"sc-ctrl-btn\"\n onClick={handlePlayPause}\n style={{\n padding: `${8 * responsiveScale}px`,\n borderRadius: \"50%\",\n minWidth: `${36 * responsiveScale}px`,\n minHeight: `${36 * responsiveScale}px`,\n }}\n title={isPlaying ? \"Pause\" : \"Play\"}\n >\n {isPlaying ? (\n <FaPause size={Math.max(14, 18 * responsiveScale)} />\n ) : (\n <FaPlay size={Math.max(14, 18 * responsiveScale)} style={{ marginLeft: \"2px\" }} />\n )}\n </button>\n\n {/* Volume Group - YouTube Style */}\n <div\n style={{\n display: \"flex\",\n alignItems: \"center\",\n paddingRight: `${6 * responsiveScale}px`,\n }}\n onMouseEnter={() => setShowVolumeSlider(true)}\n onMouseLeave={() => setShowVolumeSlider(false)}\n >\n <button\n className=\"sc-ctrl-btn\"\n onClick={() => {\n if (playerRef.current) {\n playerRef.current.toggleMute();\n }\n onVolumeToggle?.();\n resetControlsTimer();\n }}\n style={{\n padding: `${8 * responsiveScale}px`,\n borderRadius: \"50%\",\n minWidth: `${36 * responsiveScale}px`,\n minHeight: `${36 * responsiveScale}px`,\n }}\n title={isMuted ? \"Unmute\" : \"Mute\"}\n >\n <VolumeIcon size={Math.max(14, 18 * responsiveScale)} />\n </button>\n <div\n style={{\n width: showVolumeSlider ? `${68 * responsiveScale}px` : \"0px\",\n overflow: \"hidden\",\n transition: \"width 0.2s cubic-bezier(0.4, 0, 0.2, 1)\",\n display: \"flex\",\n alignItems: \"center\",\n paddingLeft: showVolumeSlider ? `${3 * responsiveScale}px` : \"0\",\n paddingRight: showVolumeSlider ? `${8 * responsiveScale}px` : \"0\",\n }}\n >\n <div\n style={{\n position: \"relative\",\n width: `${56 * responsiveScale}px`,\n height: \"3px\",\n cursor: \"pointer\",\n borderRadius: \"1.5px\",\n }}\n onMouseDown={(e) => {\n e.preventDefault();\n const el = e.currentTarget;\n const move = (ev: MouseEvent) => {\n const r = el.getBoundingClientRect();\n handleVolumeChange(Math.max(0, Math.min(1, (ev.clientX - r.left) / r.width)));\n };\n const up = () => { document.removeEventListener(\"mousemove\", move); document.removeEventListener(\"mouseup\", up); };\n document.addEventListener(\"mousemove\", move);\n document.addEventListener(\"mouseup\", up);\n const r = el.getBoundingClientRect();\n handleVolumeChange(Math.max(0, Math.min(1, (e.clientX - r.left) / r.width)));\n }}\n onClick={(e) => {\n e.stopPropagation();\n const r = e.currentTarget.getBoundingClientRect();\n handleVolumeChange(Math.max(0, Math.min(1, (e.clientX - r.left) / r.width)));\n }}\n >\n <div style={{ position: \"absolute\", inset: 0, background: \"rgba(255, 255, 255, 0.2)\", borderRadius: \"1.5px\" }} />\n <div\n style={{\n position: \"absolute\",\n top: 0, left: 0, bottom: 0,\n width: `${(isMuted ? 0 : volume) * 100}%`,\n background: \"#fff\",\n borderRadius: \"1.5px\",\n transition: \"width 0.1s ease-out\",\n }}\n />\n <div\n style={{\n position: \"absolute\",\n top: \"50%\",\n left: `${(isMuted ? 0 : volume) * 100}%`,\n transform: \"translate(-50%, -50%)\",\n width: \"12px\",\n height: \"12px\",\n background: \"#fff\",\n borderRadius: \"50%\",\n boxShadow: \"0 0 3px rgba(0, 0, 0, 0.3)\",\n transition: \"left 0.1s ease-out\",\n }}\n />\n </div>\n </div>\n </div>\n\n {/* Time Display */}\n <div\n style={{\n fontSize: `${13 * responsiveScale}px`,\n fontFamily: \"Roboto, 'Segoe UI', Arial, sans-serif\",\n color: \"rgba(255, 255, 255, 0.9)\",\n display: viewportWidth < 480 ? \"none\" : \"block\",\n fontVariantNumeric: \"tabular-nums\",\n userSelect: \"none\",\n marginLeft: `${4 * responsiveScale}px`,\n }}\n >\n {formatTime(currentTime)}{\" \"}\n <span style={{ color: \"rgba(255,255,255,0.5)\" }}>/</span>{\" \"}\n {formatTime(duration)}\n </div>\n </div>\n\n <div\n style={{\n display: \"flex\",\n alignItems: \"center\",\n gap: `${8 * responsiveScale}px`,\n }}\n >\n {(showAdsControl ?? true) && (\n <button\n className=\"sc-ctrl-btn\"\n onClick={() => {\n const next = !adsDisabled;\n setAdsDisabled(next);\n playerRef.current?.setDisableAds(next);\n resetControlsTimer();\n }}\n style={{\n padding: `${8 * responsiveScale}px`,\n borderRadius: \"50%\",\n minWidth: `${36 * responsiveScale}px`,\n minHeight: `${36 * responsiveScale}px`,\n background: adsDisabled\n ? \"rgba(239, 68, 68, 0.28)\"\n : \"transparent\",\n fontFamily: \"'SF Mono', 'Cascadia Code', monospace\",\n fontSize: `${12 * responsiveScale}px`,\n fontWeight: 700,\n letterSpacing: \"0.03em\",\n color: adsDisabled\n ? \"rgba(252, 165, 165, 0.9)\"\n : \"rgba(255, 255, 255, 0.75)\",\n textDecoration: adsDisabled ? \"line-through\" : \"none\",\n }}\n title={adsDisabled ? \"Enable ads\" : \"Disable ads\"}\n >\n AD\n </button>\n )}\n\n {swirlProjectId && (showOverlaysControl ?? true) && (\n <button\n className=\"sc-ctrl-btn\"\n onClick={() => {\n setOverlaysDisabled((prev) => !prev);\n resetControlsTimer();\n }}\n style={{\n padding: `${8 * responsiveScale}px`,\n borderRadius: \"50%\",\n minWidth: `${36 * responsiveScale}px`,\n minHeight: `${36 * responsiveScale}px`,\n background: overlaysDisabled\n ? \"rgba(239, 68, 68, 0.28)\"\n : \"transparent\",\n color: overlaysDisabled\n ? \"rgba(252, 165, 165, 0.9)\"\n : \"rgba(255, 255, 255, 0.75)\",\n opacity: overlaysDisabled ? 1 : 0.9,\n }}\n title={overlaysDisabled ? \"Enable overlays\" : \"Disable overlays\"}\n >\n <FaLayerGroup size={Math.max(14, 18 * responsiveScale)} />\n </button>\n )}\n\n {(swirlProjectId || adcisionChannelId) && (showAiContextControl ?? true) && (\n <button\n className=\"sc-ctrl-btn\"\n onClick={() => {\n setShowAiPanel((prev) => !prev);\n resetControlsTimer();\n }}\n style={{\n padding: `${8 * responsiveScale}px`,\n borderRadius: \"50%\",\n minWidth: `${36 * responsiveScale}px`,\n minHeight: `${36 * responsiveScale}px`,\n background: showAiPanel\n ? \"rgba(236, 72, 153, 0.34)\"\n : \"transparent\",\n fontFamily: \"'SF Mono', 'Cascadia Code', monospace\",\n fontSize: `${12 * responsiveScale}px`,\n fontWeight: 700,\n letterSpacing: \"0.03em\",\n }}\n title={\n showAiPanel\n ? \"Hide AI context\"\n : \"Show AI context\"\n }\n >\n AI\n </button>\n )}\n\n {(showDebugControl ?? true) && (\n <button\n className=\"sc-ctrl-btn\"\n onClick={() => {\n setShowDebugPanel((prev) => !prev);\n resetControlsTimer();\n }}\n style={{\n padding: `${8 * responsiveScale}px`,\n borderRadius: \"50%\",\n minWidth: `${36 * responsiveScale}px`,\n minHeight: `${36 * responsiveScale}px`,\n background: showDebugPanel\n ? \"rgba(255, 255, 255, 0.16)\"\n : \"transparent\",\n }}\n title={showDebugPanel ? \"Hide debug panel\" : \"Show debug panel\"}\n >\n <FaCog size={Math.max(14, 18 * responsiveScale)} />\n </button>\n )}\n\n {/* Speed Selector */}\n <div style={{ position: \"relative\", display: viewportWidth < 600 ? \"none\" : \"block\" }}>\n <button\n className=\"sc-ctrl-btn\"\n onClick={() => { setShowSpeedMenu(!showSpeedMenu); resetControlsTimer(); }}\n style={{\n padding: `${6 * responsiveScale}px ${10 * responsiveScale}px`,\n borderRadius: `${6 * responsiveScale}px`,\n fontSize: `${13 * responsiveScale}px`,\n fontFamily: \"'SF Mono', 'Cascadia Code', monospace\",\n fontWeight: \"600\",\n minHeight: `${32 * responsiveScale}px`,\n }}\n title=\"Playback Speed\"\n >\n {playbackRate}x\n </button>\n\n {showSpeedMenu && (\n <div\n style={{\n position: \"absolute\",\n bottom: \"100%\",\n right: 0,\n marginBottom: \"8px\",\n background: \"rgba(0, 0, 0, 0.8)\",\n backdropFilter: \"blur(24px)\",\n WebkitBackdropFilter: \"blur(24px)\",\n borderRadius: \"10px\",\n border: \"1px solid rgba(255, 255, 255, 0.1)\",\n overflow: \"hidden\",\n minWidth: \"80px\",\n boxShadow: \"0 12px 40px rgba(0, 0, 0, 0.5)\",\n animation: \"sc-fade-in 0.15s ease\",\n }}\n >\n {[0.25, 0.5, 0.75, 1, 1.25, 1.5, 1.75, 2].map((speed) => (\n <button\n key={speed}\n onClick={() => handlePlaybackRateChange(speed)}\n style={{\n display: \"block\",\n width: \"100%\",\n padding: `${8 * responsiveScale}px ${14 * responsiveScale}px`,\n background: playbackRate === speed\n ? \"rgba(255, 255, 255, 0.12)\"\n : \"transparent\",\n border: \"none\",\n color: playbackRate === speed ? \"#fff\" : \"rgba(255, 255, 255, 0.7)\",\n cursor: \"pointer\",\n fontSize: `${12 * responsiveScale}px`,\n fontFamily: \"'SF Mono', monospace\",\n fontWeight: playbackRate === speed ? \"700\" : \"500\",\n textAlign: \"center\",\n transition: \"background 0.15s ease, color 0.15s ease\",\n }}\n onMouseEnter={(e) => {\n if (playbackRate !== speed) {\n (e.target as HTMLElement).style.background = \"rgba(255, 255, 255, 0.08)\";\n (e.target as HTMLElement).style.color = \"#fff\";\n }\n }}\n onMouseLeave={(e) => {\n if (playbackRate !== speed) {\n (e.target as HTMLElement).style.background = \"transparent\";\n (e.target as HTMLElement).style.color = \"rgba(255, 255, 255, 0.7)\";\n }\n }}\n >\n {speed}x\n </button>\n ))}\n </div>\n )}\n </div>\n\n {/* Fullscreen */}\n <button\n className=\"sc-ctrl-btn\"\n onClick={() => {\n if (onFullscreenToggle) {\n onFullscreenToggle();\n } else if (wrapperRef.current) {\n if (!document.fullscreenElement) {\n wrapperRef.current.requestFullscreen().catch(() => {});\n } else {\n document.exitFullscreen().catch(() => {});\n }\n }\n resetControlsTimer();\n }}\n style={{\n padding: `${8 * responsiveScale}px`,\n borderRadius: \"50%\",\n minWidth: `${36 * responsiveScale}px`,\n minHeight: `${36 * responsiveScale}px`,\n }}\n title={isFullscreen ? \"Exit Fullscreen\" : \"Enter Fullscreen\"}\n >\n {isFullscreen ? (\n <FaCompress size={Math.max(14, 18 * responsiveScale)} />\n ) : (\n <FaExpand size={Math.max(14, 18 * responsiveScale)} />\n )}\n </button>\n </div>\n </div>\n </div>\n ) : (\n showCustomControls && !showLicenseWarning && (\n <div\n className=\"sc-controls-bar\"\n style={{\n position: \"absolute\",\n bottom: `${10 * responsiveScale}px`,\n right: `${10 * responsiveScale}px`,\n display: \"flex\",\n flexDirection: isPortrait ? \"column\" : \"row\",\n gap: `${8 * responsiveScale}px`,\n zIndex: 10,\n opacity: controlsVisible ? 1 : 0,\n transform: controlsVisible ? \"translateY(0)\" : \"translateY(4px)\",\n pointerEvents: controlsVisible ? \"auto\" : \"none\",\n }}\n >\n {/* Minimal Volume Control - YouTube Style */}\n <div\n style={{\n display: \"flex\",\n alignItems: \"center\",\n background: \"rgba(0, 0, 0, 0.6)\",\n borderRadius: `${18 * responsiveScale}px`,\n padding: \"2px\",\n paddingRight: `${8 * responsiveScale}px`,\n }}\n onMouseEnter={() => setShowVolumeSlider(true)}\n onMouseLeave={() => setShowVolumeSlider(false)}\n >\n <button\n className=\"sc-ctrl-btn\"\n onClick={() => {\n if (playerRef.current) playerRef.current.toggleMute();\n onVolumeToggle?.();\n resetControlsTimer();\n }}\n style={{\n padding: `${8 * responsiveScale}px`,\n borderRadius: \"50%\",\n minWidth: `${36 * responsiveScale}px`,\n minHeight: `${36 * responsiveScale}px`,\n }}\n title={isMuted ? \"Unmute\" : \"Mute\"}\n >\n <VolumeIcon size={Math.max(14, 18 * responsiveScale)} />\n </button>\n <div\n style={{\n width: showVolumeSlider ? `${68 * responsiveScale}px` : \"0px\",\n overflow: \"hidden\",\n transition: \"width 0.2s cubic-bezier(0.4, 0, 0.2, 1)\",\n display: \"flex\",\n alignItems: \"center\",\n paddingLeft: showVolumeSlider ? `${3 * responsiveScale}px` : \"0\",\n paddingRight: showVolumeSlider ? `${10 * responsiveScale}px` : \"0\",\n }}\n >\n <div\n style={{\n position: \"relative\",\n width: `${56 * responsiveScale}px`,\n height: \"3px\",\n cursor: \"pointer\",\n borderRadius: \"1.5px\",\n }}\n onMouseDown={(e) => {\n e.preventDefault();\n const el = e.currentTarget;\n const move = (ev: MouseEvent) => {\n const r = el.getBoundingClientRect();\n handleVolumeChange(Math.max(0, Math.min(1, (ev.clientX - r.left) / r.width)));\n };\n const up = () => { document.removeEventListener(\"mousemove\", move); document.removeEventListener(\"mouseup\", up); };\n document.addEventListener(\"mousemove\", move);\n document.addEventListener(\"mouseup\", up);\n const r = el.getBoundingClientRect();\n handleVolumeChange(Math.max(0, Math.min(1, (e.clientX - r.left) / r.width)));\n }}\n onClick={(e) => {\n e.stopPropagation();\n const r = e.currentTarget.getBoundingClientRect();\n handleVolumeChange(Math.max(0, Math.min(1, (e.clientX - r.left) / r.width)));\n }}\n >\n <div style={{ position: \"absolute\", inset: 0, background: \"rgba(255, 255, 255, 0.2)\", borderRadius: \"1.5px\" }} />\n <div\n style={{\n position: \"absolute\",\n top: 0, left: 0, bottom: 0,\n width: `${(isMuted ? 0 : volume) * 100}%`,\n background: \"#fff\",\n borderRadius: \"1.5px\",\n transition: \"width 0.1s ease-out\",\n }}\n />\n <div\n style={{\n position: \"absolute\",\n top: \"50%\",\n left: `${(isMuted ? 0 : volume) * 100}%`,\n transform: \"translate(-50%, -50%)\",\n width: \"12px\",\n height: \"12px\",\n background: \"#fff\",\n borderRadius: \"50%\",\n boxShadow: \"0 0 3px rgba(0, 0, 0, 0.3)\",\n transition: \"left 0.1s ease-out\",\n }}\n />\n </div>\n </div>\n </div>\n\n {(showAdsControl ?? true) && (\n <button\n className=\"sc-ctrl-btn\"\n onClick={() => {\n const next = !adsDisabled;\n setAdsDisabled(next);\n playerRef.current?.setDisableAds(next);\n resetControlsTimer();\n }}\n style={{\n padding: `${8 * responsiveScale}px`,\n borderRadius: \"50%\",\n minWidth: `${36 * responsiveScale}px`,\n minHeight: `${36 * responsiveScale}px`,\n background: adsDisabled\n ? \"rgba(239, 68, 68, 0.28)\"\n : \"rgba(0, 0, 0, 0.6)\",\n fontFamily: \"'SF Mono', 'Cascadia Code', monospace\",\n fontSize: `${12 * responsiveScale}px`,\n fontWeight: 700,\n letterSpacing: \"0.03em\",\n color: adsDisabled\n ? \"rgba(252, 165, 165, 0.9)\"\n : \"rgba(255, 255, 255, 0.75)\",\n textDecoration: adsDisabled ? \"line-through\" : \"none\",\n }}\n title={adsDisabled ? \"Enable ads\" : \"Disable ads\"}\n >\n AD\n </button>\n )}\n\n {swirlProjectId && (showOverlaysControl ?? true) && (\n <button\n className=\"sc-ctrl-btn\"\n onClick={() => {\n setOverlaysDisabled((prev) => !prev);\n resetControlsTimer();\n }}\n style={{\n padding: `${8 * responsiveScale}px`,\n borderRadius: \"50%\",\n minWidth: `${36 * responsiveScale}px`,\n minHeight: `${36 * responsiveScale}px`,\n background: overlaysDisabled\n ? \"rgba(239, 68, 68, 0.28)\"\n : \"rgba(0, 0, 0, 0.6)\",\n color: overlaysDisabled\n ? \"rgba(252, 165, 165, 0.9)\"\n : \"rgba(255, 255, 255, 0.75)\",\n }}\n title={overlaysDisabled ? \"Enable overlays\" : \"Disable overlays\"}\n >\n <FaLayerGroup size={Math.max(14, 18 * responsiveScale)} />\n </button>\n )}\n\n {(swirlProjectId || adcisionChannelId) && (showAiContextControl ?? true) && (\n <button\n className=\"sc-ctrl-btn\"\n onClick={() => {\n setShowAiPanel((prev) => !prev);\n resetControlsTimer();\n }}\n style={{\n padding: `${8 * responsiveScale}px`,\n borderRadius: \"50%\",\n minWidth: `${36 * responsiveScale}px`,\n minHeight: `${36 * responsiveScale}px`,\n background: showAiPanel\n ? \"rgba(236, 72, 153, 0.34)\"\n : \"rgba(0, 0, 0, 0.6)\",\n fontFamily: \"'SF Mono', 'Cascadia Code', monospace\",\n fontSize: `${12 * responsiveScale}px`,\n fontWeight: 700,\n letterSpacing: \"0.03em\",\n }}\n title={\n showAiPanel\n ? \"Hide AI context\"\n : \"Show AI context\"\n }\n >\n AI\n </button>\n )}\n\n {(showDebugControl ?? true) && (\n <button\n className=\"sc-ctrl-btn\"\n onClick={() => {\n setShowDebugPanel((prev) => !prev);\n resetControlsTimer();\n }}\n style={{\n padding: `${8 * responsiveScale}px`,\n borderRadius: \"50%\",\n minWidth: `${36 * responsiveScale}px`,\n minHeight: `${36 * responsiveScale}px`,\n background: showDebugPanel\n ? \"rgba(255, 255, 255, 0.16)\"\n : \"rgba(0, 0, 0, 0.6)\",\n }}\n title={showDebugPanel ? \"Hide debug panel\" : \"Show debug panel\"}\n >\n <FaCog size={Math.max(14, 18 * responsiveScale)} />\n </button>\n )}\n\n {/* Minimal Fullscreen */}\n <button\n className=\"sc-ctrl-btn\"\n onClick={() => {\n if (onFullscreenToggle) {\n onFullscreenToggle();\n } else if (wrapperRef.current) {\n if (!document.fullscreenElement) {\n wrapperRef.current.requestFullscreen().catch(() => {});\n } else {\n document.exitFullscreen().catch(() => {});\n }\n }\n resetControlsTimer();\n }}\n style={{\n padding: `${8 * responsiveScale}px`,\n borderRadius: \"50%\",\n minWidth: `${36 * responsiveScale}px`,\n minHeight: `${36 * responsiveScale}px`,\n background: \"rgba(0, 0, 0, 0.6)\",\n }}\n title={isFullscreen ? \"Exit Fullscreen\" : \"Enter Fullscreen\"}\n >\n {isFullscreen ? (\n <FaCompress size={Math.max(14, 18 * responsiveScale)} />\n ) : (\n <FaExpand size={Math.max(14, 18 * responsiveScale)} />\n )}\n </button>\n </div>\n )\n )}\n\n {/* Click overlay for onControlClick */}\n {onControlClick && (\n <div\n onClick={onControlClick}\n style={{\n position: \"absolute\",\n top: 0,\n left: 0,\n right: 0,\n bottom: 0,\n zIndex: 1,\n cursor: \"pointer\",\n }}\n />\n )}\n </div>\n </>\n );\n },\n (prevProps, nextProps) => {\n for (const prop of CRITICAL_PROPS) {\n if ((prevProps as any)[prop] !== (nextProps as any)[prop]) {\n return false;\n }\n }\n\n const uiProps = [\n \"autoplay\",\n \"muted\",\n \"controls\",\n \"showCustomControls\",\n \"className\",\n \"style\",\n \"wrapperClassName\",\n \"wrapperStyle\",\n \"playsInline\",\n \"preload\",\n \"poster\",\n \"children\",\n \"swirlProjectId\",\n \"swirlShowcaseDemo\",\n \"swirlOverlayApiBaseUrl\",\n \"swirlOverlayCoordinateSpace\",\n \"adcisionChannelId\",\n \"disableOverlays\",\n \"showAdsControl\",\n \"showOverlaysControl\",\n \"showAiContextControl\",\n \"showDebugControl\",\n ] as const;\n\n for (const prop of uiProps) {\n if ((prevProps as any)[prop] !== (nextProps as any)[prop]) {\n return false;\n }\n }\n\n const callbackProps = [\n \"onReady\",\n \"onVolumeToggle\",\n \"onFullscreenToggle\",\n \"onControlClick\",\n ] as const;\n for (const prop of callbackProps) {\n if ((prevProps as any)[prop] !== (nextProps as any)[prop]) {\n return false;\n }\n }\n\n return true;\n }\n );\n","import Hls from \"hls.js\";\nimport type {\n StormcloudVideoPlayerConfig,\n AdBreakContext,\n AdInsertionPointResponse,\n} from \"../types\";\nimport type { VastBidResponse } from \"../types\";\nimport { createAdStormPlayer } from \"../sdk/adstormPlayer\";\nimport type { AdStormAdLayer } from \"../sdk/adstormPlayer\";\nimport {\n sendInitialTracking,\n sendHeartbeat,\n sendAdLoadedTracking,\n sendAdImpressionTracking,\n} from \"../utils/tracking\";\nimport { initializePolyfills } from \"../utils/polyfills\";\nimport { logBrowserInfo, getBrowserConfigOverrides, detectBrowser } from \"../utils/browserCompat\";\n\nconst DEBUG_HISTORY_LIMIT = 120;\n\ntype DebugLogLevel = \"info\" | \"warn\" | \"error\";\n\ninterface DebugLogEntry {\n timestampMs: number;\n level: DebugLogLevel;\n category: string;\n message: string;\n details?: Record<string, unknown>;\n}\n\ntype AdInsertionDebugEvent =\n | \"api_response\"\n | \"scte35_inserted\"\n | \"segment_found\"\n | \"segment_playing\"\n | \"ad_scheduled\"\n | \"ad_triggered\";\n\ninterface AdInsertionDebugEntry {\n timestampMs: number;\n event: AdInsertionDebugEvent;\n segmentName: string;\n offsetSeconds?: number;\n updatedAt?: string;\n detail?: string;\n}\n\nexport class StormcloudVideoPlayer {\n private readonly video: HTMLVideoElement;\n private readonly config: StormcloudVideoPlayerConfig;\n private hls?: Hls;\n private adLayer: AdStormAdLayer;\n private pendingNextAdBids: VastBidResponse[] | null = null;\n private continuousFetchLoopPromise: Promise<void> | null = null;\n private attached = false;\n private inAdBreak = false;\n private currentAdBreakStartWallClockMs: number | undefined;\n private expectedAdBreakDurationMs: number | undefined;\n private adStopTimerId: number | undefined;\n private adFailsafeTimerId: number | undefined;\n private adPodQueue: string[] = [];\n private lastHeartbeatTime: number = 0;\n private heartbeatInterval: number | undefined;\n private currentAdIndex: number = 0;\n private totalAdsInBreak: number = 0;\n private showAds: boolean = false;\n private isLiveStream: boolean = false;\n private nativeHlsMode: boolean = false;\n private videoSrcProtection: string | null = null;\n private bufferedSegmentsCount: number = 0;\n private shouldAutoplayAfterBuffering: boolean = false;\n private hasInitialBufferCompleted: boolean = false;\n private activeAdRequestToken: number | null = null;\n private adRequestWatchdogId: number | undefined;\n private adRequestWatchdogToken: number | null = null;\n private adFailsafeToken: number | null = null;\n private continuousFetchingActive: boolean = false;\n private isInAdTransition: boolean = false;\n private maxPlaceholderDurationMs: number = 5000;\n private isShowingPlaceholder: boolean = false;\n private timeUpdateHandler?: (event: Event) => void;\n private emptiedHandler?: (event: Event) => void;\n\n private adInsertionPollingId: number | undefined;\n private lastAdInsertionPoint: AdInsertionPointResponse | null = null;\n private processedAdInsertionUpdatedAt: string | null = null;\n private adInsertionOffsetTimerId: number | undefined;\n\n private totalAdRequestsInBreak: number = 0;\n private readonly maxTotalAdRequestsPerBreak: number = 20;\n \n private pendingAdBreak: {\n durationSeconds?: number;\n detectedAtFragmentSn?: number;\n isFetching: boolean;\n fetchStartTime?: number;\n } | null = null;\n private prefetchTimerId: number | undefined;\n private savedMutedStateBeforeAd: { muted: boolean; volume: number } | null = null;\n\n private adLayerInitialized: boolean = false;\n private consecutiveFailures: number = 0;\n private readonly maxConsecutiveFailures: number = 5;\n private lastAdRequestTime: number = 0;\n private readonly minAdRequestIntervalMs: number = 2500;\n private readonly backoffBaseMs: number = 1000;\n private readonly maxBackoffMs: number = 15000;\n private readonly adTransitionGapMs: number;\n private readonly MIN_AD_REMAINING_MS: number = 15000;\n private readonly adRequestTimeoutMs: number = 5000;\n private readonly adRequestMaxRetries: number = 3;\n private readonly adRequestRetryBackoffMs: number = 1500;\n private preloadedTokens: string[] = [];\n private fillerVideo: HTMLVideoElement | undefined;\n private fillerBreakTimerId: ReturnType<typeof setTimeout> | undefined;\n private debugLogEntries: DebugLogEntry[] = [];\n private adInsertionDebugHistory: AdInsertionDebugEntry[] = [];\n\n constructor(config: StormcloudVideoPlayerConfig) {\n initializePolyfills();\n\n const browserOverrides = getBrowserConfigOverrides();\n \n this.config = { ...browserOverrides, ...config };\n this.video = config.videoElement;\n this.adTransitionGapMs = this.config.adTransitionGapMs ?? 100;\n\n logBrowserInfo(config.debugAdTiming);\n\n const browserForAdLayer = detectBrowser();\n const isSinglePipeline = browserForAdLayer.isSmartTV || !!this.config.singlePipelineMode;\n this.adLayer = createAdStormPlayer(this.video, {\n licenseKey: this.config.licenseKey || \"\",\n debug: !!config.debugAdTiming,\n ...(this.config.channelId != null && { channelId: this.config.channelId }),\n });\n this.adLayer.updateOptions({\n continueLiveStreamDuringAds: !isSinglePipeline && this.shouldContinueLiveStreamDuringAds(),\n });\n }\n\n private async adRequest(context?: AdBreakContext): Promise<VastBidResponse[]> {\n if (this.config.disableAds) return [];\n const durationSeconds = Math.max(\n 1,\n Math.ceil(context?.remainingBreakSec ?? context?.breakDurationSec ?? 30)\n );\n await this.adLayer.requestAds(String(durationSeconds));\n return [\n {\n bidder: \"adstorm-direct\",\n cpm: 0,\n width: 0,\n height: 0,\n adId: \"adstorm\",\n impId: \"\",\n creativeId: \"adstorm\",\n currency: \"USD\",\n durationSec: durationSeconds,\n },\n ];\n }\n\n async load(): Promise<void> {\n if (!this.attached) {\n this.attach();\n }\n\n this.initializeTracking();\n\n if (this.shouldUseNativeHls()) {\n this.nativeHlsMode = true;\n this.videoSrcProtection = this.config.src;\n this.video.src = this.config.src;\n\n this.isLiveStream = this.config.lowLatencyMode ?? false;\n\n if (this.config.debugAdTiming) {\n console.log(\n \"[StormcloudVideoPlayer] Using native HLS playback - VOD mode:\",\n {\n isLive: this.isLiveStream,\n allowNativeHls: this.config.allowNativeHls,\n adBehavior: \"vod (main video pauses during ads)\",\n }\n );\n }\n\n if (!this.config.disableAds) {\n this.adLayer.updateOptions({ continueLiveStreamDuringAds: false, mainHlsInstance: null });\n }\n\n if (this.config.autoplay) {\n await this.video.play()?.catch(() => {});\n }\n return;\n }\n\n this.hls = new Hls({\n enableWorker: true,\n backBufferLength: 30,\n liveDurationInfinity: true,\n lowLatencyMode: !!this.config.lowLatencyMode,\n maxLiveSyncPlaybackRate: this.config.lowLatencyMode ? 1.5 : 1.0,\n ...(this.config.lowLatencyMode ? { liveSyncDuration: 2 } : {}),\n maxBufferLength: 30,\n maxMaxBufferLength: 600,\n maxBufferSize: 60 * 1000 * 1000,\n maxBufferHole: 0.5,\n highBufferWatchdogPeriod: 2,\n nudgeOffset: 0.1,\n nudgeMaxRetry: 3,\n startPosition: -1,\n });\n\n this.hls.on(Hls.Events.MEDIA_ATTACHED, () => {\n this.hls?.loadSource(this.config.src);\n });\n\n this.hls.on(Hls.Events.MANIFEST_PARSED, async (_, data: any) => {\n if (this.config.allowNativeHls === false) {\n this.isLiveStream = true;\n } else {\n this.isLiveStream =\n this.hls?.levels?.some(\n (level) =>\n level?.details?.live === true || level?.details?.type === \"LIVE\"\n ) ?? false;\n }\n\n if (this.config.debugAdTiming) {\n const adBehavior = this.shouldContinueLiveStreamDuringAds()\n ? \"live (main video continues muted during ads)\"\n : \"vod (main video pauses during ads)\";\n console.log(\"[StormcloudVideoPlayer] Stream type detected:\", {\n isLive: this.isLiveStream,\n allowNativeHls: this.config.allowNativeHls,\n adBehavior,\n });\n }\n\n if (!this.config.disableAds) {\n this.adLayer.updateOptions({\n continueLiveStreamDuringAds: this.shouldContinueLiveStreamDuringAds(),\n mainHlsInstance: this.hls ?? null,\n });\n }\n\n this.bufferedSegmentsCount = 0;\n this.hasInitialBufferCompleted = false;\n this.shouldAutoplayAfterBuffering = !!this.config.autoplay;\n\n const minSegments = this.config.minSegmentsBeforePlay ?? 2;\n\n if (this.config.debugAdTiming) {\n console.log(\n \"[StormcloudVideoPlayer] Waiting for\",\n minSegments,\n \"segments to buffer before playback\"\n );\n }\n\n if (minSegments === 0 || !this.config.autoplay) {\n this.hasInitialBufferCompleted = true;\n if (this.config.autoplay) {\n await this.video.play()?.catch(() => {});\n }\n }\n\n if (!this.config.disableAds && this.config.projectId) {\n this.startAdInsertionPolling();\n }\n });\n\n this.hls.on(Hls.Events.LEVEL_LOADED, () => {\n if (this.inAdBreak || this.pendingAdBreak) {\n return;\n }\n this.checkAdInsertionInManifest();\n });\n\n this.hls.on(Hls.Events.FRAG_BUFFERED, async (_evt, data: any) => {\n if (this.hasInitialBufferCompleted) {\n return;\n }\n\n this.bufferedSegmentsCount++;\n const minSegments = this.config.minSegmentsBeforePlay ?? 2;\n\n if (this.config.debugAdTiming) {\n console.log(\n `[StormcloudVideoPlayer] Buffered segment ${this.bufferedSegmentsCount}/${minSegments}`\n );\n }\n\n if (this.bufferedSegmentsCount >= minSegments) {\n this.hasInitialBufferCompleted = true;\n\n if (this.shouldAutoplayAfterBuffering) {\n if (this.inAdBreak || this.adLayer.isAdPlaying()) {\n if (this.config.debugAdTiming) {\n console.log(\n `[StormcloudVideoPlayer] Initial buffer complete (${this.bufferedSegmentsCount} segments). Ad break active — deferring play() to handleAdPodComplete().`\n );\n }\n } else {\n if (this.config.debugAdTiming) {\n console.log(\n `[StormcloudVideoPlayer] Initial buffer complete (${this.bufferedSegmentsCount} segments). Starting playback.`\n );\n }\n await this.video.play()?.catch((err) => {\n if (this.config.debugAdTiming) {\n console.warn(\"[StormcloudVideoPlayer] Autoplay failed:\", err);\n }\n });\n }\n }\n }\n });\n\n this.hls.on(Hls.Events.FRAG_CHANGED, (_evt, data: any) => {\n const frag = data?.frag;\n if (!frag) return;\n\n if (\n this.lastAdInsertionPoint &&\n !this.inAdBreak &&\n this.lastAdInsertionPoint.updated_at !== this.processedAdInsertionUpdatedAt\n ) {\n const segmentName = this.lastAdInsertionPoint.segment_ts_name;\n if (this.fragmentMatchesSegment(frag, segmentName)) {\n this.processedAdInsertionUpdatedAt = this.lastAdInsertionPoint.updated_at;\n const offsetMs = (this.lastAdInsertionPoint.offset_seconds || 0) * 1000;\n const durationSeconds = this.pendingAdBreak?.durationSeconds ?? 60;\n const withPrefetch = this.pendingAdBreak != null;\n\n this.pushAdInsertionDebug(\"segment_playing\", segmentName, {\n offsetSeconds: this.lastAdInsertionPoint.offset_seconds,\n detail: `sn=${frag?.sn ?? \"?\"}${withPrefetch ? \" (prefetch active)\" : \"\"}`,\n });\n\n if (this.config.debugAdTiming) {\n console.log(\n `[StormcloudVideoPlayer] Ad insertion segment \"${segmentName}\" now playing — scheduling ad start in ${offsetMs}ms` +\n (withPrefetch ? \" (prefetch was active, preloaded tokens will be used)\" : \"\")\n );\n }\n\n this.pushAdInsertionDebug(\"ad_scheduled\", segmentName, {\n offsetSeconds: this.lastAdInsertionPoint.offset_seconds,\n detail: `in ${offsetMs}ms, dur=${durationSeconds}s${withPrefetch ? \" (with prefetch)\" : \"\"}`,\n });\n\n this.clearAdInsertionOffsetTimer();\n this.adInsertionOffsetTimerId = window.setTimeout(() => {\n this.adInsertionOffsetTimerId = undefined;\n if (this.inAdBreak) return;\n\n this.pushAdInsertionDebug(\"ad_triggered\", segmentName, {\n detail: `ad break started (${durationSeconds}s${withPrefetch ? \", with prefetch\" : \"\"})`,\n });\n\n void this.handleAdStart(durationSeconds);\n }, offsetMs);\n }\n }\n });\n\n this.hls.on(Hls.Events.FRAG_PARSING_USERDATA, (_evt, data: any) => {\n const samples: Array<{ data: Uint8Array }> = data?.samples ?? [];\n for (const sample of samples) {\n const bytes = sample?.data;\n if (!bytes || bytes.length < 5) continue;\n // SCTE-35 splice_info_section starts with 0xFC (table_id)\n const isSCTE35 = bytes[0] === 0xfc;\n if (!isSCTE35) continue;\n const segName = data?.frag?.relurl ?? data?.frag?.url ?? \"\";\n this.pushAdInsertionDebug(\"scte35_inserted\", segName, {\n detail: `len=${bytes.length}B`,\n });\n }\n });\n\n this.hls.on(Hls.Events.ERROR, (_evt, data) => {\n if (data?.fatal) {\n switch (data.type) {\n case Hls.ErrorTypes.NETWORK_ERROR:\n this.hls?.startLoad();\n break;\n case Hls.ErrorTypes.MEDIA_ERROR:\n this.hls?.recoverMediaError();\n break;\n default:\n this.destroy();\n break;\n }\n }\n });\n\n this.hls.attachMedia(this.video);\n }\n\n private getAdSource(): \"vast\" {\n return \"vast\";\n }\n\n private attachAdLayerEventListeners(): void {\n this.adLayer.on(\"ad_impression\", () => {\n if (this.config.licenseKey) {\n sendAdImpressionTracking(this.config.licenseKey, {\n source: this.getAdSource(),\n adIndex: this.currentAdIndex,\n timestamp: new Date().toISOString(),\n });\n }\n });\n this.adLayer.on(\"ad_error\", (errorPayload?: any) => {\n let errorMessage = \"Ad playback failed\";\n \n if (errorPayload) {\n const errorCode = errorPayload.code || errorPayload.errorCode || \"unknown\";\n const vastErrorCode = errorPayload.vastErrorCode;\n const message = errorPayload.message || errorPayload.errorMessage || \"Unknown error\";\n const cause = errorPayload.cause || errorPayload.innerError || errorPayload.error;\n \n errorMessage = `Ad error: AdError ${errorCode}: ${message}`;\n \n if (vastErrorCode && vastErrorCode !== \"N/A\" && vastErrorCode !== errorCode) {\n errorMessage += ` (VAST Error Code: ${vastErrorCode})`;\n }\n \n if (cause) {\n const causeMessage = typeof cause === \"string\" ? cause : (cause.message || String(cause));\n errorMessage += `. Caused by: ${causeMessage}`;\n }\n }\n \n this.pushDebugLog(\"error\", \"ad\", errorMessage, {\n ...(errorPayload ? { payload: errorPayload as Record<string, unknown> } : {}),\n });\n console.error(\"[AD-ERROR]\", errorMessage, errorPayload || \"\");\n this.adLayer.stop().catch(() => {});\n this.handleAdFailure();\n });\n this.adLayer.on(\"content_pause\", () => {\n this.clearAdFailsafeTimer();\n this.clearAdRequestWatchdog();\n this.activeAdRequestToken = null;\n this.showAds = true;\n\n if (this.config.disableFiller) {\n if (this.savedMutedStateBeforeAd == null) {\n this.savedMutedStateBeforeAd = { muted: this.video.muted, volume: this.video.volume };\n this.adLayer.updateOriginalMutedState(this.video.muted, this.video.volume);\n }\n if (!this.video.muted) {\n this.video.muted = true;\n this.video.volume = 0;\n }\n this.adLayer.showPlaceholder();\n }\n \n if (this.inAdBreak && this.expectedAdBreakDurationMs != null && this.adStopTimerId == null) {\n this.scheduleAdStopCountdown(this.getRemainingAdMs());\n if (this.config.debugAdTiming) {\n console.log(\"[StormcloudVideoPlayer] Starting ad break timer on content_pause (first ad starting)\");\n }\n }\n\n this.adLayer.setAdVolume(\n this.adLayer.getOriginalMutedState() ? 1 : this.adLayer.getOriginalVolume()\n );\n\n this.stopFillerBreakTimer();\n this.hidePlaceholderLayer();\n this.isShowingPlaceholder = false;\n if (this.config.debugAdTiming) {\n console.log(\"[StormcloudVideoPlayer] Hiding placeholder - new ads starting\");\n }\n });\n this.adLayer.on(\"content_resume\", () => {\n const remaining = this.getRemainingAdMs();\n const breakMuted = this.savedMutedStateBeforeAd?.muted ?? this.adLayer.getOriginalMutedState();\n const breakVolume = this.savedMutedStateBeforeAd?.volume ?? this.adLayer.getOriginalVolume();\n if (this.config.debugAdTiming) {\n console.log(\n \"[StormcloudVideoPlayer] content_resume received, inAdBreak=%s, remaining=%s, preloadedTokens=%d, pendingNext=%s\",\n this.inAdBreak,\n remaining,\n this.preloadedTokens.length,\n !!this.pendingNextAdBids\n );\n }\n\n this.clearAdFailsafeTimer();\n this.clearAdRequestWatchdog();\n this.activeAdRequestToken = null;\n this.showAds = false;\n\n if (!this.inAdBreak) {\n this.video.style.visibility = \"visible\";\n this.video.style.opacity = \"1\";\n this.syncMainContentAudioWhenVisible();\n return;\n }\n\n this.consecutiveFailures = 0;\n\n if (!this.config.disableFiller && !this.video.muted) {\n this.video.muted = true;\n this.video.volume = 0;\n }\n\n if (this.preloadedTokens.length > 0) {\n const token = this.preloadedTokens.shift()!;\n const remainingNow = this.getRemainingAdMs();\n if (this.expectedAdBreakDurationMs != null && remainingNow < this.MIN_AD_REMAINING_MS) {\n if (this.config.debugAdTiming) {\n console.log(\"[StormcloudVideoPlayer] content_resume: skip preloaded ad, only\", remainingNow, \"ms left\");\n }\n this.adLayer.cancelPreload(token);\n } else {\n this.video.style.transition = \"none\";\n this.video.style.opacity = \"0\";\n this.video.style.visibility = \"hidden\";\n if (!this.config.singlePipelineMode) {\n this.showPlaceholderLayer();\n }\n this.adLayer.showPlaceholder();\n this.isInAdTransition = true;\n setTimeout(() => {\n this.isInAdTransition = false;\n if (!this.inAdBreak) return;\n this.currentAdIndex++;\n this.adLayer.playPreloaded(token).catch((err) => {\n if (this.config.debugAdTiming) console.warn(\"[StormcloudVideoPlayer] playPreloaded failed:\", err);\n this.handleAdFailure();\n });\n }, this.adTransitionGapMs);\n return;\n }\n }\n\n if (this.pendingNextAdBids && this.pendingNextAdBids.length > 0) {\n const bids = [...this.pendingNextAdBids];\n this.pendingNextAdBids = null;\n const remainingNow = this.getRemainingAdMs();\n if (this.expectedAdBreakDurationMs != null && remainingNow < this.MIN_AD_REMAINING_MS) {\n if (this.config.debugAdTiming) {\n console.log(\"[StormcloudVideoPlayer] content_resume: skip pending bids, only\", remainingNow, \"ms left\");\n }\n } else {\n this.video.style.transition = \"none\";\n this.video.style.opacity = \"0\";\n this.video.style.visibility = \"hidden\";\n if (!this.config.singlePipelineMode) {\n this.showPlaceholderLayer();\n }\n this.adLayer.showPlaceholder();\n this.isInAdTransition = true;\n setTimeout(() => {\n this.isInAdTransition = false;\n if (!this.inAdBreak || bids.length === 0) return;\n const freshBids = this.pendingNextAdBids ?? bids;\n this.pendingNextAdBids = null;\n this.currentAdIndex++;\n this.adLayer.playAd(freshBids).catch((err) => {\n if (this.config.debugAdTiming) console.warn(\"[StormcloudVideoPlayer] playAd(pending) failed:\", err);\n this.handleAdFailure();\n });\n }, this.adTransitionGapMs);\n return;\n }\n }\n\n const remainingFinal = this.getRemainingAdMs();\n if (this.inAdBreak && remainingFinal > this.MIN_AD_REMAINING_MS) {\n if (this.config.debugAdTiming) {\n console.log(\"[StormcloudVideoPlayer] content_resume: ad ended/failed with time remaining, showing filler and continuing fetch for\", remainingFinal, \"ms\");\n }\n if (!this.config.disableFiller) {\n this.showPlaceholderLayer();\n this.adLayer.showPlaceholder();\n } else {\n this.video.style.transition = \"none\";\n this.video.style.opacity = \"0\";\n this.video.style.visibility = \"hidden\";\n this.adLayer.showPlaceholder();\n }\n\n this.continuousFetchingActive = true;\n this.startContinuousFetchLoop();\n return;\n }\n\n if (this.config.debugAdTiming) {\n console.log(\"[StormcloudVideoPlayer] content_resume: no more ads, ending ad pod\");\n }\n this.handleAdPodComplete();\n });\n }\n\n private ensureFillerVideo(): void {\n if (this.fillerVideo) return;\n if (!this.video.parentElement) return;\n\n const filler = document.createElement(\"video\");\n filler.src = \"https://f000.backblazeb2.com/file/AdStormAds/384/Sonifi_Filler.mp4\";\n filler.loop = true;\n filler.muted = false;\n filler.playsInline = true;\n filler.style.position = \"absolute\";\n filler.style.left = \"0\";\n filler.style.top = \"0\";\n filler.style.width = \"100%\";\n filler.style.height = \"100%\";\n filler.style.objectFit = \"cover\";\n filler.style.zIndex = \"20\";\n filler.style.display = \"none\";\n filler.preload = \"auto\";\n this.video.parentElement.appendChild(filler);\n this.fillerVideo = filler;\n }\n\n private showPlaceholderLayer(): void {\n if (this.config.disableFiller) return;\n this.ensureFillerVideo();\n if (!this.fillerVideo) return;\n\n if (!this.video.muted) {\n this.video.muted = true;\n this.video.volume = 0;\n }\n\n this.fillerVideo.style.display = \"block\";\n this.fillerVideo.play().catch(() => {\n if (this.fillerVideo) {\n this.fillerVideo.style.display = \"none\";\n }\n if (!this.adLayer.isAdPlaying()) {\n if (this.config.debugAdTiming) {\n console.log(\"[StormcloudVideoPlayer] Filler video failed — restoring main video\");\n }\n this.adLayer.hidePlaceholder();\n if (this.video.paused && this.video.readyState >= 2) {\n this.video.play()?.catch(() => {});\n }\n }\n });\n\n if (this.config.debugAdTiming) {\n console.log(\"[StormcloudVideoPlayer] Showing filler video layer\");\n }\n }\n\n private hidePlaceholderLayer(): void {\n if (!this.fillerVideo) return;\n\n this.fillerVideo.style.display = \"none\";\n this.fillerVideo.pause();\n this.fillerVideo.currentTime = 0;\n\n if (this.config.debugAdTiming) {\n console.log(\"[StormcloudVideoPlayer] Hiding filler video layer\");\n }\n }\n\n private startFillerBreakTimer(durationMs: number): void {\n this.stopFillerBreakTimer();\n this.showPlaceholderLayer();\n this.fillerBreakTimerId = setTimeout(() => {\n this.fillerBreakTimerId = undefined;\n this.hidePlaceholderLayer();\n if (this.inAdBreak) this.handleAdPodComplete();\n }, durationMs);\n }\n\n private stopFillerBreakTimer(): void {\n if (this.fillerBreakTimerId !== undefined) {\n clearTimeout(this.fillerBreakTimerId);\n this.fillerBreakTimerId = undefined;\n }\n }\n\n private attach(): void {\n if (this.attached) return;\n this.attached = true;\n this.video.autoplay = !!this.config.autoplay;\n this.video.muted = !!this.config.muted;\n\n if (!this.config.disableAds) {\n this.initializeAdLayer();\n }\n\n this.timeUpdateHandler = () => {\n this.onTimeUpdate(this.video.currentTime);\n };\n this.video.addEventListener(\"timeupdate\", this.timeUpdateHandler);\n\n this.emptiedHandler = () => {\n if (\n this.nativeHlsMode &&\n this.videoSrcProtection &&\n !this.adLayer.isAdPlaying()\n ) {\n if (this.config.debugAdTiming) {\n console.log(\n \"[StormcloudVideoPlayer] Video src was cleared, restoring:\",\n this.videoSrcProtection\n );\n }\n const currentTime = this.video.currentTime;\n const wasPaused = this.video.paused;\n this.video.src = this.videoSrcProtection;\n this.video.currentTime = currentTime;\n if (!wasPaused) {\n this.video.play().catch(() => {});\n }\n }\n };\n this.video.addEventListener(\"emptied\", this.emptiedHandler);\n }\n\n private shouldUseNativeHls(): boolean {\n const streamType = this.getStreamType();\n\n if (streamType === \"other\") {\n return true;\n }\n\n const canNative = this.video.canPlayType(\"application/vnd.apple.mpegurl\");\n return !!(this.config.allowNativeHls && canNative);\n }\n\n private initializeTracking(): void {\n sendInitialTracking(this.config.licenseKey)\n .then(() => {\n this.heartbeatInterval = window.setInterval(() => {\n this.sendHeartbeatIfNeeded();\n }, 5000);\n })\n .catch((error) => {\n if (this.config.debugAdTiming) {\n console.warn(\n \"[StormcloudVideoPlayer] Failed to send initial tracking:\",\n error\n );\n }\n this.heartbeatInterval = window.setInterval(() => {\n this.sendHeartbeatIfNeeded();\n }, 5000);\n });\n }\n\n private sendHeartbeatIfNeeded(): void {\n const now = Date.now();\n if (!this.lastHeartbeatTime || now - this.lastHeartbeatTime > 30000) {\n this.lastHeartbeatTime = now;\n sendHeartbeat(this.config.licenseKey).catch((error) => {\n if (this.config.debugAdTiming) {\n console.warn(\n \"[StormcloudVideoPlayer] Failed to send heartbeat:\",\n error\n );\n }\n });\n }\n }\n\n getCurrentAdIndex(): number {\n return this.currentAdIndex;\n }\n\n getTotalAdsInBreak(): number {\n return this.totalAdsInBreak;\n }\n\n getRemainingAdSeconds(): number {\n const remainingMs = this.getRemainingAdMs();\n if (\n !Number.isFinite(remainingMs) ||\n remainingMs <= 0 ||\n remainingMs === Number.MAX_SAFE_INTEGER\n ) {\n return 0;\n }\n return Math.ceil(remainingMs / 1000);\n }\n\n isAdPlaying(): boolean {\n return this.inAdBreak && this.adLayer.isAdPlaying();\n }\n\n isShowingAds(): boolean {\n return this.showAds;\n }\n\n isInAdBreak(): boolean {\n return this.inAdBreak;\n }\n\n private initializeAdLayer(): void {\n if (this.adLayerInitialized) return;\n this.adLayer.initialize();\n if (!this.config.disableFiller) {\n this.ensureFillerVideo();\n }\n this.adLayer.updateOriginalMutedState(this.video.muted, this.video.volume);\n this.attachAdLayerEventListeners();\n this.adLayerInitialized = true;\n }\n\n setDisableAds(disabled: boolean): void {\n this.config.disableAds = disabled;\n if (!disabled && this.attached) {\n this.initializeAdLayer();\n }\n if (this.config.debugAdTiming) {\n console.log(\"[StormcloudVideoPlayer] setDisableAds:\", disabled);\n }\n }\n\n private syncMainContentAudioWhenVisible(): void {\n const adLayerShowing = this.showAds || this.adLayer.isAdPlaying();\n if (adLayerShowing) return;\n const muted = this.adLayer.getOriginalMutedState();\n const volume = this.adLayer.getOriginalVolume();\n if (this.video.muted !== muted) this.video.muted = muted;\n if (Math.abs(this.video.volume - volume) > 0.01) this.video.volume = volume;\n }\n\n getStreamType(): \"hls\" | \"other\" {\n const url = this.config.src.toLowerCase();\n if (\n url.includes(\".m3u8\") ||\n url.includes(\"/hls/\") ||\n url.includes(\"application/vnd.apple.mpegurl\")\n ) {\n return \"hls\";\n }\n return \"other\";\n }\n\n shouldShowNativeControls(): boolean {\n const streamType = this.getStreamType();\n if (streamType === \"other\") {\n return !(this.config.showCustomControls ?? false);\n }\n return !!(\n this.config.allowNativeHls && !(this.config.showCustomControls ?? false)\n );\n }\n\n private shouldContinueLiveStreamDuringAds(): boolean {\n if (this.config.allowNativeHls) {\n return false;\n }\n\n if (!this.isLiveStream) {\n return false;\n }\n\n if (this.config.singlePipelineMode) {\n return false;\n }\n\n const browser = detectBrowser();\n if (browser.isSmartTV) {\n return false;\n }\n\n return true;\n }\n\n private startAdPrefetch(durationSeconds?: number, fragmentSn?: number): void {\n if (this.config.disableAds) return;\n if (this.pendingAdBreak || this.inAdBreak) {\n return;\n }\n\n this.pendingAdBreak = {\n ...(durationSeconds !== undefined ? { durationSeconds } : {}),\n ...(fragmentSn !== undefined ? { detectedAtFragmentSn: fragmentSn } : {}),\n isFetching: false,\n fetchStartTime: Date.now(),\n };\n\n void this.runAdPrefetch(durationSeconds);\n\n if (this.config.debugAdTiming) {\n console.log(\"[PREFETCH] Ad break registered, multi-ad prefetch started\");\n }\n }\n\n private async runAdPrefetch(durationSeconds?: number): Promise<void> {\n const durSec = durationSeconds ?? 60;\n\n const context: AdBreakContext = {\n breakDurationSec: durSec,\n remainingBreakSec: durSec,\n };\n\n let firstBids: VastBidResponse[];\n try {\n firstBids = await this.adRequest({ ...context, adIndex: 1 });\n } catch {\n firstBids = [];\n }\n\n if (this.inAdBreak) return;\n\n if (firstBids.length === 0) {\n if (this.config.debugAdTiming) {\n console.log(\"[PREFETCH] First VAST request returned no ad, aborting prefetch\");\n }\n this.clearPendingAdBreak();\n return;\n }\n\n const adDurationSec = firstBids[0]?.durationSec ?? 30;\n const estimatedCount = Math.max(1, Math.ceil(durSec / adDurationSec));\n\n if (this.config.debugAdTiming) {\n console.log(\n `[PREFETCH] Ad duration=${adDurationSec}s, break=${durSec}s → ${estimatedCount} ad(s) needed`\n );\n }\n\n const firstToken = `preload_${Date.now()}_${Math.random().toString(36).slice(2, 7)}`;\n try {\n await this.adLayer.preloadAd(firstBids, firstToken);\n if (!this.inAdBreak) {\n this.preloadedTokens.push(firstToken);\n if (this.config.debugAdTiming) {\n console.log(`[PREFETCH] First ad preloaded and queued, token=${firstToken}`);\n }\n }\n } catch {\n if (this.config.debugAdTiming) {\n console.warn(`[PREFETCH] First ad preload failed, token=${firstToken}`);\n }\n }\n\n if (estimatedCount > 1) {\n type SettledResult = { ok: true; value: VastBidResponse[] } | { ok: false };\n const remaining: Promise<SettledResult>[] = Array.from(\n { length: estimatedCount - 1 },\n (_, i) =>\n this.adRequest({ ...context, adIndex: i + 2 })\n .then((bids): SettledResult => ({ ok: true, value: bids }))\n .catch((): SettledResult => ({ ok: false }))\n );\n\n const results = await Promise.all(remaining);\n\n for (const result of results) {\n if (this.inAdBreak) break;\n if (result.ok && result.value.length > 0) {\n const token = `preload_${Date.now()}_${Math.random().toString(36).slice(2, 7)}`;\n try {\n await this.adLayer.preloadAd(result.value, token);\n if (!this.inAdBreak) {\n this.preloadedTokens.push(token);\n if (this.config.debugAdTiming) {\n console.log(`[PREFETCH] Additional ad preloaded and queued, token=${token}`);\n }\n }\n } catch {\n if (this.config.debugAdTiming) {\n console.warn(`[PREFETCH] Additional ad preload failed, token=${token}`);\n }\n }\n }\n }\n }\n\n if (this.config.debugAdTiming) {\n console.log(`[PREFETCH] Pre-fetch complete: ${this.preloadedTokens.length} ad(s) queued`);\n }\n }\n\n private clearPendingAdBreak(): void {\n if (this.prefetchTimerId != null) {\n clearTimeout(this.prefetchTimerId);\n this.prefetchTimerId = undefined;\n }\n this.pendingAdBreak = null;\n }\n\n private cancelAndClearPreloadedTokens(): void {\n for (const token of this.preloadedTokens) {\n this.adLayer.cancelPreload(token);\n }\n this.preloadedTokens = [];\n }\n\n private startAdInsertionPolling(): void {\n if (this.adInsertionPollingId != null) return;\n this.fetchAdInsertionPoint();\n this.adInsertionPollingId = window.setInterval(() => {\n this.fetchAdInsertionPoint();\n }, 1000);\n }\n\n private stopAdInsertionPolling(): void {\n if (this.adInsertionPollingId != null) {\n clearInterval(this.adInsertionPollingId);\n this.adInsertionPollingId = undefined;\n }\n }\n\n private async fetchAdInsertionPoint(): Promise<void> {\n if (!this.config.projectId) return;\n try {\n const resp = await fetch(\n `https://adstorm.co/api-adstorm-dev/adstorm/adcision/channels/${encodeURIComponent(this.config.projectId)}/ad-insertion-point`\n );\n if (!resp.ok) return;\n const data: AdInsertionPointResponse = await resp.json();\n const prevSegment = this.lastAdInsertionPoint?.segment_ts_name;\n const isNew = data.updated_at !== this.lastAdInsertionPoint?.updated_at;\n const segmentChanged = prevSegment !== data.segment_ts_name;\n this.lastAdInsertionPoint = data;\n\n if (isNew) {\n this.pushAdInsertionDebug(\"api_response\", data.segment_ts_name, {\n offsetSeconds: data.offset_seconds,\n updatedAt: data.updated_at,\n detail: `ch=${data.channel_id}`,\n });\n\n if (segmentChanged && (this.pendingAdBreak || this.adInsertionOffsetTimerId != null)) {\n this.clearAdInsertionOffsetTimer();\n this.clearPendingAdBreak();\n this.cancelAndClearPreloadedTokens();\n if (this.config.debugAdTiming) {\n console.log(\n `[StormcloudVideoPlayer] Insertion segment changed (${prevSegment} → ${data.segment_ts_name}), stale pending state cleared`\n );\n }\n }\n\n this.checkAdInsertionInManifest();\n }\n\n if (this.config.debugAdTiming) {\n console.log(\"[StormcloudVideoPlayer] Ad insertion point API response:\", data);\n }\n } catch {\n if (this.config.debugAdTiming) {\n console.warn(\"[StormcloudVideoPlayer] Ad insertion point API fetch failed\");\n }\n }\n }\n\n private checkAdInsertionInManifest(): void {\n if (!this.lastAdInsertionPoint) return;\n if (this.inAdBreak || this.pendingAdBreak) return;\n if (this.lastAdInsertionPoint.updated_at === this.processedAdInsertionUpdatedAt) return;\n\n const segmentName = this.lastAdInsertionPoint.segment_ts_name;\n const levels = this.hls?.levels;\n if (!levels) return;\n\n for (const level of levels) {\n const fragments = (level as any).details?.fragments;\n if (!Array.isArray(fragments)) continue;\n\n for (const frag of fragments) {\n if (this.fragmentMatchesSegment(frag, segmentName)) {\n const currentTime = this.video.currentTime;\n const fragStart: number = frag.start ?? 0;\n const fragDuration: number = frag.duration ?? 0;\n const isCurrentlyPlaying =\n fragDuration > 0 &&\n currentTime >= fragStart &&\n currentTime < fragStart + fragDuration;\n\n this.pushAdInsertionDebug(\"segment_found\", segmentName, {\n detail: `sn=${frag?.sn ?? \"?\"} ${isCurrentlyPlaying ? \"(playing)\" : \"(future)\"}`,\n });\n\n if (this.config.debugAdTiming) {\n console.log(\n `[StormcloudVideoPlayer] Ad insertion segment \"${segmentName}\" found in manifest — ` +\n (isCurrentlyPlaying ? \"currently playing, scheduling directly\" : \"starting pre-fetch\")\n );\n }\n\n this.startAdPrefetch(60, frag?.sn);\n\n if (isCurrentlyPlaying && !this.inAdBreak) {\n this.processedAdInsertionUpdatedAt = this.lastAdInsertionPoint.updated_at;\n\n const rawOffsetMs = (this.lastAdInsertionPoint.offset_seconds ?? 0) * 1000;\n const elapsedInFragMs = (currentTime - fragStart) * 1000;\n const remainingOffsetMs = Math.max(0, rawOffsetMs - elapsedInFragMs);\n\n this.pushAdInsertionDebug(\"segment_playing\", segmentName, {\n offsetSeconds: this.lastAdInsertionPoint.offset_seconds,\n detail: `sn=${frag?.sn ?? \"?\"} (caught in manifest check)`,\n });\n\n this.pushAdInsertionDebug(\"ad_scheduled\", segmentName, {\n offsetSeconds: this.lastAdInsertionPoint.offset_seconds,\n detail: `in ${remainingOffsetMs}ms (adjusted for elapsed ${Math.round(elapsedInFragMs)}ms)`,\n });\n\n this.clearAdInsertionOffsetTimer();\n this.adInsertionOffsetTimerId = window.setTimeout(() => {\n this.adInsertionOffsetTimerId = undefined;\n if (this.inAdBreak) return;\n\n this.pushAdInsertionDebug(\"ad_triggered\", segmentName, {\n detail: \"ad break started (60s, via manifest-check path)\",\n });\n\n void this.handleAdStart(60);\n }, remainingOffsetMs);\n }\n\n return;\n }\n }\n }\n }\n\n private extractTsFilename(url: string): string {\n const clean = url.includes(\"?\") ? url.slice(0, url.indexOf(\"?\")) : url;\n const parts = clean.split(\"/\");\n return parts[parts.length - 1] ?? clean;\n }\n\n private fragmentMatchesSegment(frag: any, segmentName: string): boolean {\n const rawUrl: string = frag?.url || frag?.relurl || \"\";\n if (!rawUrl) return false;\n return this.extractTsFilename(rawUrl) === this.extractTsFilename(segmentName);\n }\n\n private clearAdInsertionOffsetTimer(): void {\n if (this.adInsertionOffsetTimerId != null) {\n clearTimeout(this.adInsertionOffsetTimerId);\n this.adInsertionOffsetTimerId = undefined;\n }\n }\n\n private startContinuousFetchLoop(): void {\n if (this.continuousFetchLoopPromise != null) return;\n this.continuousFetchLoopPromise = this.runContinuousFetchLoop();\n }\n\n private async runContinuousFetchLoop(): Promise<void> {\n const backoffMs = () => {\n const mult = Math.pow(2, this.consecutiveFailures);\n return Math.min(this.backoffBaseMs * mult, this.maxBackoffMs);\n };\n while (this.inAdBreak && this.continuousFetchingActive) {\n if (this.consecutiveFailures >= this.maxConsecutiveFailures) break;\n if (this.totalAdRequestsInBreak >= this.maxTotalAdRequestsPerBreak) break;\n\n if (this.adLayer.isAdPlaying() || this.isInAdTransition) {\n if (this.pendingNextAdBids == null) {\n try {\n const remaining = this.getRemainingAdMs();\n const prefetchContext: AdBreakContext | undefined = this.expectedAdBreakDurationMs != null\n ? {\n breakDurationSec: this.expectedAdBreakDurationMs / 1000,\n remainingBreakSec: remaining / 1000,\n adIndex: this.currentAdIndex + 1,\n }\n : undefined;\n if (this.config.debugAdTiming) {\n console.log(\"[CONTINUOUS-FETCH] Pre-fetching next ad during playback, remaining:\", remaining, \"ms\");\n }\n const bids = await this.adRequest(prefetchContext);\n this.lastAdRequestTime = Date.now();\n if (!this.inAdBreak) break;\n if (bids.length > 0) {\n this.consecutiveFailures = 0;\n this.pendingNextAdBids = bids;\n this.totalAdsInBreak = Math.max(\n this.totalAdsInBreak,\n this.currentAdIndex + this.preloadedTokens.length + 1\n );\n if (this.config.debugAdTiming) {\n console.log(\"[CONTINUOUS-FETCH] Pre-fetched next ad stored as pending\");\n }\n } else {\n this.consecutiveFailures++;\n }\n } catch (err) {\n this.consecutiveFailures++;\n if (this.config.debugAdTiming) {\n console.warn(\"[CONTINUOUS-FETCH] Pre-fetch adRequest failed:\", err);\n }\n }\n } else {\n await new Promise((r) => setTimeout(r, 200));\n }\n continue;\n }\n\n if (this.pendingNextAdBids != null && this.pendingNextAdBids.length > 0) {\n const bids = this.pendingNextAdBids;\n this.pendingNextAdBids = null;\n const remainingNow = this.getRemainingAdMs();\n if (this.expectedAdBreakDurationMs == null || remainingNow >= this.MIN_AD_REMAINING_MS) {\n this.currentAdIndex++;\n if (this.config.licenseKey) {\n sendAdLoadedTracking(this.config.licenseKey, {\n source: this.getAdSource(),\n timestamp: new Date().toISOString(),\n });\n }\n await this.adLayer.playAd(bids);\n if (this.expectedAdBreakDurationMs != null && this.adStopTimerId == null) {\n this.scheduleAdStopCountdown(this.getRemainingAdMs());\n }\n this.adLayer.setAdVolume(\n this.adLayer.getOriginalMutedState() ? 1 : this.adLayer.getOriginalVolume()\n );\n } else if (this.config.debugAdTiming) {\n console.log(\"[CONTINUOUS-FETCH] Discarding pre-fetched bids: only\", remainingNow, \"ms left\");\n }\n continue;\n }\n\n const urgentNeedAd = this.inAdBreak && !this.adLayer.isAdPlaying();\n const delay = this.lastAdRequestTime\n ? this.minAdRequestIntervalMs + (!urgentNeedAd && this.consecutiveFailures > 0 ? backoffMs() : 0)\n : 0;\n const elapsed = Date.now() - this.lastAdRequestTime;\n if (elapsed < delay && this.lastAdRequestTime > 0) {\n await new Promise((r) => setTimeout(r, delay - elapsed));\n }\n if (!this.inAdBreak || !this.continuousFetchingActive) break;\n try {\n const remaining = this.getRemainingAdMs();\n const context: AdBreakContext | undefined = this.expectedAdBreakDurationMs != null\n ? {\n breakDurationSec: this.expectedAdBreakDurationMs / 1000,\n remainingBreakSec: remaining / 1000,\n adIndex: this.currentAdIndex + 1,\n }\n : undefined;\n const bids = await this.adRequest(context);\n this.lastAdRequestTime = Date.now();\n if (!this.inAdBreak) break;\n if (bids.length > 0) {\n this.consecutiveFailures = 0;\n if (this.adLayer.isAdPlaying() || this.isInAdTransition) {\n this.pendingNextAdBids = bids;\n this.totalAdsInBreak = Math.max(\n this.totalAdsInBreak,\n this.currentAdIndex + this.preloadedTokens.length + 1\n );\n if (this.config.debugAdTiming) {\n console.log(\"[CONTINUOUS-FETCH] Next ad response stored (ad currently playing or in transition)\");\n }\n } else {\n const remainingNow = this.getRemainingAdMs();\n if (this.expectedAdBreakDurationMs != null && remainingNow < this.MIN_AD_REMAINING_MS) {\n if (this.config.debugAdTiming) {\n console.log(\"[CONTINUOUS-FETCH] Skipping ad from loop: only\", remainingNow, \"ms left\");\n }\n } else {\n this.currentAdIndex++;\n if (this.config.licenseKey) {\n sendAdLoadedTracking(this.config.licenseKey, {\n source: this.getAdSource(),\n timestamp: new Date().toISOString(),\n });\n }\n await this.adLayer.playAd(bids);\n if (this.expectedAdBreakDurationMs != null && this.adStopTimerId == null) {\n this.scheduleAdStopCountdown(this.getRemainingAdMs());\n }\n this.adLayer.setAdVolume(\n this.adLayer.getOriginalMutedState() ? 1 : this.adLayer.getOriginalVolume()\n );\n }\n }\n } else {\n this.consecutiveFailures++;\n }\n } catch (err) {\n this.consecutiveFailures++;\n if (this.config.debugAdTiming) {\n console.warn(\"[CONTINUOUS-FETCH] adRequest failed:\", err);\n }\n }\n const sleepMs = (this.inAdBreak && !this.adLayer.isAdPlaying())\n ? 0\n : backoffMs();\n await new Promise((r) => setTimeout(r, sleepMs));\n }\n this.continuousFetchLoopPromise = null;\n }\n\n private async handleAdStart(durationSeconds?: number): Promise<void> {\n const adBreakDurationMs = durationSeconds != null ? durationSeconds * 1000 : undefined;\n\n if (this.config.debugAdTiming) {\n const mode = this.isLiveStream ? \"LIVE\" : \"VOD\";\n console.log(\n `[CONTINUOUS-FETCH] 📺 ${mode} MODE: Target duration=${adBreakDurationMs}ms`\n );\n }\n\n this.consecutiveFailures = 0;\n this.continuousFetchingActive = true;\n this.continuousFetchLoopPromise = null;\n this.pendingNextAdBids = null;\n this.isShowingPlaceholder = false;\n this.totalAdRequestsInBreak = 0;\n\n if (this.savedMutedStateBeforeAd == null && !this.video.muted) {\n this.savedMutedStateBeforeAd = {\n muted: false,\n volume: this.video.volume,\n };\n }\n\n const state = this.savedMutedStateBeforeAd ?? {\n muted: this.video.muted,\n volume: this.video.volume,\n };\n this.adLayer.updateOriginalMutedState(state.muted, state.volume);\n\n if (!this.config.disableFiller && !this.video.muted) {\n this.video.muted = true;\n this.video.volume = 0;\n if (this.config.debugAdTiming) {\n console.log(\"[StormcloudVideoPlayer] Muted video in handleAdStart\");\n }\n }\n\n this.inAdBreak = true;\n this.currentAdBreakStartWallClockMs = Date.now();\n this.currentAdIndex = 0;\n this.totalAdsInBreak = Math.max(1, this.preloadedTokens.length);\n this.adPodQueue = [];\n\n if (!this.config.disableFiller) this.showAds = true;\n\n if (adBreakDurationMs != null) {\n this.startFillerBreakTimer(adBreakDurationMs);\n } else if (!this.config.disableFiller && this.preloadedTokens.length === 0) {\n this.showPlaceholderLayer();\n }\n if (!this.config.disableFiller) this.adLayer.showPlaceholder();\n\n if (this.expectedAdBreakDurationMs == null && adBreakDurationMs != null) {\n this.expectedAdBreakDurationMs = adBreakDurationMs;\n }\n\n if (this.expectedAdBreakDurationMs != null) {\n this.scheduleAdStopCountdown(this.expectedAdBreakDurationMs);\n }\n\n this.clearPendingAdBreak();\n\n const adBreakToken = Date.now();\n this.activeAdRequestToken = adBreakToken;\n this.startAdFailsafeTimer(adBreakToken);\n this.startAdRequestWatchdog(adBreakToken);\n\n const adVolume = state.muted ? 1 : state.volume;\n\n if (this.preloadedTokens.length > 0) {\n const token = this.preloadedTokens.shift()!;\n if (this.config.debugAdTiming) {\n console.log(\"[CONTINUOUS-FETCH] ✅ Playing pre-buffered ad, token=\", token);\n }\n const remaining = this.getRemainingAdMs();\n if (this.expectedAdBreakDurationMs == null || remaining >= this.MIN_AD_REMAINING_MS) {\n this.currentAdIndex++;\n if (this.config.licenseKey) {\n sendAdLoadedTracking(this.config.licenseKey, {\n source: this.getAdSource(),\n timestamp: new Date().toISOString(),\n });\n }\n try {\n await this.adLayer.playPreloaded(token);\n if (this.expectedAdBreakDurationMs != null && this.adStopTimerId == null) {\n this.scheduleAdStopCountdown(this.getRemainingAdMs());\n }\n this.adLayer.setAdVolume(adVolume);\n } catch (err) {\n if (this.config.debugAdTiming) console.warn(\"[CONTINUOUS-FETCH] playPreloaded failed:\", err);\n this.consecutiveFailures++;\n await this.showPlaceholderAndWaitForAds();\n }\n } else {\n if (this.config.debugAdTiming) {\n console.log(\"[CONTINUOUS-FETCH] Skipping ad: only\", remaining, \"ms left in break\");\n }\n this.adLayer.cancelPreload(token);\n await this.showPlaceholderAndWaitForAds();\n }\n }\n\n this.startContinuousFetchLoop();\n }\n\n private stopContinuousFetching(): void {\n this.continuousFetchingActive = false;\n\n if (this.config.debugAdTiming) {\n console.log(\"[CONTINUOUS-FETCH] 🛑 Stopping continuous ad fetching\");\n }\n }\n\n private async tryNextAvailableAdWithRateLimit(): Promise<void> {\n if (this.consecutiveFailures >= this.maxConsecutiveFailures) {\n if (this.config.debugAdTiming) {\n console.log(`[CONTINUOUS-FETCH] 🛑 Too many consecutive failures (${this.consecutiveFailures}), ending ad break gracefully`);\n }\n this.handleAdPodComplete();\n return;\n }\n\n const backoffMultiplier = Math.pow(2, this.consecutiveFailures);\n const backoffDelay = Math.min(this.backoffBaseMs * backoffMultiplier, this.maxBackoffMs);\n const effectiveMinInterval = this.minAdRequestIntervalMs + (this.consecutiveFailures > 0 ? backoffDelay : 0);\n \n const timeSinceLastRequest = Date.now() - this.lastAdRequestTime;\n if (timeSinceLastRequest < effectiveMinInterval) {\n const waitTime = effectiveMinInterval - timeSinceLastRequest;\n if (this.config.debugAdTiming) {\n console.log(`[CONTINUOUS-FETCH] ⏳ Rate limiting: waiting ${waitTime}ms before next request (backoff: ${this.consecutiveFailures} failures)`);\n }\n await new Promise(resolve => setTimeout(resolve, waitTime));\n }\n\n return this.tryNextAvailableAd(0);\n }\n\n private async tryNextAvailableAd(_retryCount: number = 0): Promise<void> {\n if (this.totalAdRequestsInBreak >= this.maxTotalAdRequestsPerBreak) {\n if (this.config.debugAdTiming) {\n console.log(`[CONTINUOUS-FETCH] 🛑 Max ad requests per break (${this.maxTotalAdRequestsPerBreak}) reached`);\n }\n this.handleAdPodComplete();\n return;\n }\n const remaining = this.getRemainingAdMs();\n if (remaining <= 500 && this.expectedAdBreakDurationMs != null) {\n if (this.config.debugAdTiming) {\n console.log(\"[CONTINUOUS-FETCH] ⏹️ No time remaining, ending ad break\");\n }\n this.handleAdPodComplete();\n return;\n }\n\n if (this.consecutiveFailures >= this.maxConsecutiveFailures) {\n if (this.config.debugAdTiming) {\n console.log(`[CONTINUOUS-FETCH] 🛑 Too many consecutive failures (${this.consecutiveFailures}), ending ad break`);\n }\n this.handleAdPodComplete();\n return;\n }\n\n try {\n this.lastAdRequestTime = Date.now();\n const bids = await this.adRequest();\n if (!this.inAdBreak) return;\n if (bids.length > 0) {\n this.consecutiveFailures = 0;\n this.currentAdIndex++;\n this.totalAdRequestsInBreak++;\n if (this.adLayer.isAdPlaying() || this.isInAdTransition) {\n this.pendingNextAdBids = bids;\n this.totalAdsInBreak = Math.max(\n this.totalAdsInBreak,\n this.currentAdIndex + this.preloadedTokens.length\n );\n } else {\n if (this.config.licenseKey) {\n sendAdLoadedTracking(this.config.licenseKey, {\n source: this.getAdSource(),\n timestamp: new Date().toISOString(),\n });\n }\n await this.adLayer.playAd(bids);\n if (this.expectedAdBreakDurationMs != null && this.adStopTimerId == null) {\n this.scheduleAdStopCountdown(this.getRemainingAdMs());\n }\n this.adLayer.setAdVolume(\n this.adLayer.getOriginalMutedState() ? 1 : this.adLayer.getOriginalVolume()\n );\n }\n } else {\n this.consecutiveFailures++;\n await this.showPlaceholderAndWaitForAds();\n }\n } catch (error) {\n this.consecutiveFailures++;\n if (this.config.debugAdTiming) {\n console.warn(\"[CONTINUOUS-FETCH] tryNextAvailableAd request failed:\", error);\n }\n await this.showPlaceholderAndWaitForAds();\n }\n }\n\n private async showPlaceholderAndWaitForAds(): Promise<void> {\n const remaining = this.getRemainingAdMs();\n const waitTime = Math.min(this.maxPlaceholderDurationMs, remaining);\n\n if (this.consecutiveFailures >= this.maxConsecutiveFailures) {\n const stillRemaining = this.getRemainingAdMs();\n if (stillRemaining >= 1000) {\n if (this.config.debugAdTiming) {\n console.log(\"[CONTINUOUS-FETCH] 🛑 Max failures reached but break still active — resetting and continuing filler\");\n }\n this.consecutiveFailures = 0;\n return;\n }\n if (this.config.debugAdTiming) {\n console.log(\"[CONTINUOUS-FETCH] 🛑 Skipping placeholder - too many consecutive failures\");\n }\n this.handleAdPodComplete();\n return;\n }\n\n if (waitTime < 1000) {\n this.handleAdPodComplete();\n return;\n }\n\n if (this.config.debugAdTiming) {\n console.log(`[CONTINUOUS-FETCH] ⬛ Showing placeholder for ${waitTime}ms while waiting for ad response`);\n }\n\n if (!this.config.disableFiller) {\n this.isShowingPlaceholder = true;\n this.showPlaceholderLayer();\n this.adLayer.showPlaceholder();\n }\n\n const checkInterval = 300;\n const maxChecks = Math.floor(waitTime / checkInterval);\n\n for (let i = 0; i < maxChecks; i++) {\n await new Promise((resolve) => setTimeout(resolve, checkInterval));\n\n if (!this.inAdBreak) return;\n\n if (this.consecutiveFailures >= this.maxConsecutiveFailures) {\n if (this.config.debugAdTiming) {\n console.log(\"[CONTINUOUS-FETCH] 🛑 Too many failures during placeholder wait — resetting and continuing filler\");\n }\n this.consecutiveFailures = 0;\n break;\n }\n\n if (this.pendingNextAdBids != null && this.pendingNextAdBids.length > 0) {\n const bids = this.pendingNextAdBids;\n this.pendingNextAdBids = null;\n this.isShowingPlaceholder = false;\n this.adLayer.hidePlaceholder();\n this.currentAdIndex++;\n try {\n await this.adLayer.playAd(bids);\n this.consecutiveFailures = 0;\n } catch {\n this.consecutiveFailures++;\n await this.tryNextAvailableAdWithRateLimit();\n }\n return;\n }\n\n if (this.adLayer.isAdPlaying()) {\n this.isShowingPlaceholder = false;\n this.adLayer.hidePlaceholder();\n return;\n }\n }\n\n const stillRemaining = this.getRemainingAdMs();\n if (stillRemaining >= 1000) {\n if (this.config.debugAdTiming) {\n console.log(`[CONTINUOUS-FETCH] ⏰ Placeholder slot expired, ${stillRemaining}ms still remaining — continuing filler`);\n }\n this.isShowingPlaceholder = false;\n this.adLayer.hidePlaceholder();\n this.consecutiveFailures = 0;\n return;\n }\n\n if (this.config.debugAdTiming) {\n console.log(\"[CONTINUOUS-FETCH] ⏰ Placeholder timeout, ending ad break\");\n }\n\n this.isShowingPlaceholder = false;\n this.adLayer.hidePlaceholder();\n this.handleAdPodComplete();\n }\n\n private onTimeUpdate(_currentTimeSec: number): void {\n if (this.adLayer.isAdPlaying()) return;\n }\n\n private scheduleAdStopCountdown(remainingMs: number): void {\n this.clearAdStopTimer();\n const ms = Math.max(0, Math.floor(remainingMs));\n if (ms === 0) {\n this.ensureAdStoppedByTimer();\n return;\n }\n this.adStopTimerId = window.setTimeout(() => {\n this.ensureAdStoppedByTimer();\n }, ms) as unknown as number;\n }\n\n private clearAdStopTimer(): void {\n if (this.adStopTimerId != null) {\n clearTimeout(this.adStopTimerId);\n this.adStopTimerId = undefined;\n }\n }\n\n private ensureAdStoppedByTimer(): void {\n if (!this.inAdBreak) return;\n\n this.adStopTimerId = undefined;\n\n const adPlaying = this.adLayer.isAdPlaying();\n const pendingAds = this.adPodQueue.length > 0;\n const checkIntervalMs = Math.max(\n 250,\n Math.floor(this.config.adBreakCheckIntervalMs ?? 1000)\n );\n const maxExtensionMsConfig = this.config.maxAdBreakExtensionMs;\n const maxExtensionMs =\n typeof maxExtensionMsConfig === \"number\" && maxExtensionMsConfig > 0\n ? maxExtensionMsConfig\n : 60000;\n\n let elapsedSinceStartMs = 0;\n if (this.currentAdBreakStartWallClockMs != null) {\n elapsedSinceStartMs = Date.now() - this.currentAdBreakStartWallClockMs;\n }\n const expectedDurationMs = this.expectedAdBreakDurationMs ?? 0;\n const overrunMs = Math.max(0, elapsedSinceStartMs - expectedDurationMs);\n\n const shouldExtendAdBreak =\n (adPlaying || pendingAds || this.showAds) && overrunMs < maxExtensionMs;\n\n if (shouldExtendAdBreak) {\n this.scheduleAdStopCountdown(checkIntervalMs);\n return;\n }\n\n if (adPlaying) {\n this.adLayer.stop().catch(() => {});\n }\n\n this.handleAdPodComplete();\n }\n\n private handleAdPodComplete(): void {\n if (this.config.debugAdTiming) {\n console.log(\"[StormcloudVideoPlayer] 🏁 Ad pod complete - cleaning up\");\n }\n\n this.clearAdRequestWatchdog();\n this.clearAdFailsafeTimer();\n this.clearAdInsertionOffsetTimer();\n this.activeAdRequestToken = null;\n\n this.isInAdTransition = false;\n this.stopContinuousFetching();\n this.stopFillerBreakTimer();\n this.hidePlaceholderLayer();\n this.clearPendingAdBreak();\n this.cancelAndClearPreloadedTokens();\n this.pendingNextAdBids = null;\n\n if (this.isShowingPlaceholder) {\n this.adLayer.hidePlaceholder();\n this.isShowingPlaceholder = false;\n }\n\n this.inAdBreak = false;\n this.expectedAdBreakDurationMs = undefined;\n this.currentAdBreakStartWallClockMs = undefined;\n this.clearAdStopTimer();\n this.adPodQueue = [];\n this.showAds = false;\n this.currentAdIndex = 0;\n this.totalAdsInBreak = 0;\n this.totalAdRequestsInBreak = 0;\n this.consecutiveFailures = 0;\n\n const restoredMuted = this.savedMutedStateBeforeAd?.muted ?? this.adLayer.getOriginalMutedState();\n const restoredVolume = this.savedMutedStateBeforeAd?.volume ?? this.adLayer.getOriginalVolume();\n this.adLayer.updateOriginalMutedState(restoredMuted, restoredVolume);\n\n this.adLayer.stop().catch(() => {});\n\n if (this.video.muted !== restoredMuted) {\n this.video.muted = restoredMuted;\n }\n if (Math.abs(this.video.volume - restoredVolume) > 0.01) {\n this.video.volume = restoredVolume;\n }\n\n const browser = detectBrowser();\n const isSmartTV = browser.tizenVersion !== undefined || browser.webOSVersion !== undefined || !!this.config.singlePipelineMode;\n if (isSmartTV && this.hls) {\n const hlsRef = this.hls;\n const savedMuted = restoredMuted;\n const savedVolume = restoredVolume;\n const videoRef = this.video;\n const debugEnabled = this.config.debugAdTiming;\n\n const tryPlay = (attempt: number) => {\n if (this.inAdBreak || this.adLayer.isAdPlaying()) return;\n videoRef.play()?.catch(() => {\n if (attempt < 3) {\n if (debugEnabled) {\n console.log(`[StormcloudVideoPlayer] Smart TV: play() retry ${attempt + 1}/3 in ${500 * (attempt + 1)}ms`);\n }\n setTimeout(() => tryPlay(attempt + 1), 500 * (attempt + 1));\n }\n });\n };\n\n const onManifestParsedRestore = () => {\n hlsRef.off(Hls.Events.MANIFEST_PARSED, onManifestParsedRestore);\n if (!this.inAdBreak && !this.adLayer.isAdPlaying()) {\n if (videoRef.muted !== savedMuted) videoRef.muted = savedMuted;\n if (Math.abs(videoRef.volume - savedVolume) > 0.01) videoRef.volume = savedVolume;\n if (debugEnabled) {\n console.log(\"[StormcloudVideoPlayer] Smart TV: audio state restored on MANIFEST_PARSED after re-attach\");\n }\n hlsRef.startLoad(-1);\n if (debugEnabled) {\n console.log(\"[StormcloudVideoPlayer] Smart TV: seeking to live edge and resuming playback after re-attach\");\n }\n }\n };\n hlsRef.on(Hls.Events.MANIFEST_PARSED, onManifestParsedRestore);\n\n const pipelineDelayMs = 300;\n if (debugEnabled) {\n console.log(`[StormcloudVideoPlayer] Smart TV: waiting ${pipelineDelayMs}ms for hardware pipeline release before re-attach`);\n }\n setTimeout(() => {\n if (this.inAdBreak || this.adLayer.isAdPlaying()) return;\n if (this.hls) {\n this.hls.attachMedia(this.video);\n if (debugEnabled) {\n console.log(\"[StormcloudVideoPlayer] Smart TV: re-attached HLS to video element after ad break to restore media pipeline\");\n }\n }\n }, pipelineDelayMs);\n } else {\n if (this.shouldContinueLiveStreamDuringAds()) {\n if (this.config.debugAdTiming) {\n if (this.video.paused) {\n console.log(\"[StormcloudVideoPlayer] Content video paused in live mode after ads, resuming playback\");\n } else {\n console.log(\"[StormcloudVideoPlayer] Content video already playing in live mode after ads\");\n }\n }\n this.video.play()?.catch(() => {});\n } else if (this.video.paused) {\n this.video.play()?.catch(() => {});\n }\n }\n\n this.syncMainContentAudioWhenVisible();\n\n if (!restoredMuted) {\n requestAnimationFrame(() => {\n this.syncMainContentAudioWhenVisible();\n });\n setTimeout(() => {\n this.syncMainContentAudioWhenVisible();\n }, 0);\n setTimeout(() => {\n this.syncMainContentAudioWhenVisible();\n }, 50);\n setTimeout(() => {\n this.syncMainContentAudioWhenVisible();\n }, 100);\n setTimeout(() => {\n this.syncMainContentAudioWhenVisible();\n }, 150);\n }\n\n if (isSmartTV && !restoredMuted) {\n [500, 1000, 2000, 3000, 5000].forEach(delay => {\n setTimeout(() => {\n if (!this.inAdBreak && !this.adLayer.isAdPlaying()) {\n if (this.video.muted !== restoredMuted) this.video.muted = restoredMuted;\n if (Math.abs(this.video.volume - restoredVolume) > 0.01) this.video.volume = restoredVolume;\n }\n }, delay);\n });\n }\n\n this.savedMutedStateBeforeAd = null;\n }\n\n private handleAdFailure(): void {\n this.consecutiveFailures++;\n if (this.config.debugAdTiming) {\n console.log(\n `[CONTINUOUS-FETCH] Ad failure: consecutiveFailures=${this.consecutiveFailures}`\n );\n }\n if (this.consecutiveFailures >= this.maxConsecutiveFailures) {\n if (this.config.debugAdTiming) {\n console.log(`[CONTINUOUS-FETCH] 🛑 Max consecutive failures reached (${this.consecutiveFailures}), ending ad break gracefully`);\n }\n this.handleAdPodComplete();\n return;\n }\n\n if (this.inAdBreak && !this.config.disableFiller) {\n if (this.config.debugAdTiming) {\n console.log(\"[CONTINUOUS-FETCH] Ad failure in active break — showing filler while awaiting next ad\");\n }\n this.showPlaceholderLayer();\n this.adLayer.showPlaceholder();\n } else if (this.inAdBreak) {\n if (this.config.debugAdTiming) {\n console.log(\"[CONTINUOUS-FETCH] Ad failure with no filler — restoring main video temporarily\");\n }\n this.adLayer.hidePlaceholder();\n if (!this.adLayer.isAdPlaying() && this.video.paused && this.video.readyState >= 2) {\n this.video.play()?.catch(() => {});\n }\n }\n }\n\n private startAdRequestWatchdog(token: number): void {\n this.clearAdRequestWatchdog();\n\n const timeoutMs = this.config.adFailsafeTimeoutMs ?? 10000;\n this.adRequestWatchdogToken = token;\n this.adRequestWatchdogId = window.setTimeout(() => {\n if (this.adRequestWatchdogToken !== token) {\n return;\n }\n\n this.adRequestWatchdogId = undefined;\n this.adRequestWatchdogToken = null;\n if (this.activeAdRequestToken === token) {\n this.activeAdRequestToken = null;\n }\n\n this.logAdState(\"ad_request_timeout\", { token, timeoutMs });\n this.handleAdFailure();\n }, timeoutMs) as unknown as number;\n\n this.logAdState(\"ad_request_watchdog_started\", { token, timeoutMs });\n }\n\n private clearAdRequestWatchdog(): void {\n if (this.adRequestWatchdogId != null) {\n clearTimeout(this.adRequestWatchdogId);\n this.adRequestWatchdogId = undefined;\n }\n\n if (this.adRequestWatchdogToken != null) {\n this.logAdState(\"ad_request_watchdog_cleared\", {\n token: this.adRequestWatchdogToken,\n });\n this.adRequestWatchdogToken = null;\n }\n }\n\n private startAdFailsafeTimer(token: number): void {\n this.clearAdFailsafeTimer();\n\n const failsafeMs = this.config.adFailsafeTimeoutMs ?? 10000;\n this.adFailsafeToken = token;\n\n this.adFailsafeTimerId = window.setTimeout(() => {\n if (this.adFailsafeToken !== token) {\n return;\n }\n\n this.adFailsafeTimerId = undefined;\n this.adFailsafeToken = null;\n\n if (this.activeAdRequestToken === token) {\n this.activeAdRequestToken = null;\n }\n\n this.logAdState(\"ad_failsafe_triggered\", {\n token,\n failsafeMs,\n videoPaused: this.video.paused,\n imaAdPlaying: this.adLayer.isAdPlaying(),\n });\n\n this.handleAdFailure();\n }, failsafeMs) as unknown as number;\n\n this.logAdState(\"ad_failsafe_started\", { token, failsafeMs });\n }\n\n private clearAdFailsafeTimer(): void {\n if (this.adFailsafeTimerId != null) {\n clearTimeout(this.adFailsafeTimerId);\n this.logAdState(\"ad_failsafe_cleared\", { token: this.adFailsafeToken });\n this.adFailsafeTimerId = undefined;\n }\n\n this.adFailsafeToken = null;\n }\n\n private logAdState(event: string, extra: Record<string, unknown> = {}): void {\n if (!this.config.debugAdTiming) {\n return;\n }\n this.pushDebugLog(\"info\", \"ad-state\", event, extra);\n\n console.log(\"[StormcloudVideoPlayer][AdState]\", {\n event,\n timestamp: new Date().toISOString(),\n showAds: this.showAds,\n adPlaying: this.adLayer.isAdPlaying(),\n inAdBreak: this.inAdBreak,\n activeAdRequestToken: this.activeAdRequestToken,\n ...extra,\n });\n }\n\n private getRemainingAdMs(): number {\n if (this.currentAdBreakStartWallClockMs == null) return 0;\n if (this.expectedAdBreakDurationMs == null) return Number.MAX_SAFE_INTEGER;\n const elapsed = Date.now() - this.currentAdBreakStartWallClockMs;\n return Math.max(0, this.expectedAdBreakDurationMs - elapsed);\n }\n\n private pushDebugLog(\n level: DebugLogLevel,\n category: string,\n message: string,\n details?: Record<string, unknown>\n ): void {\n if (!this.config.debugAdTiming) return;\n this.debugLogEntries.push({\n timestampMs: Date.now(),\n level,\n category,\n message,\n ...(details ? { details } : {}),\n });\n if (this.debugLogEntries.length > DEBUG_HISTORY_LIMIT) {\n this.debugLogEntries = this.debugLogEntries.slice(-DEBUG_HISTORY_LIMIT);\n }\n }\n\n private pushAdInsertionDebug(\n event: AdInsertionDebugEvent,\n segmentName: string,\n opts?: { offsetSeconds?: number; updatedAt?: string; detail?: string }\n ): void {\n if (!this.config.debugAdTiming) return;\n this.adInsertionDebugHistory.push({\n timestampMs: Date.now(),\n event,\n segmentName,\n ...(opts?.offsetSeconds !== undefined ? { offsetSeconds: opts.offsetSeconds } : {}),\n ...(opts?.updatedAt ? { updatedAt: opts.updatedAt } : {}),\n ...(opts?.detail ? { detail: opts.detail } : {}),\n });\n if (this.adInsertionDebugHistory.length > DEBUG_HISTORY_LIMIT) {\n this.adInsertionDebugHistory = this.adInsertionDebugHistory.slice(-DEBUG_HISTORY_LIMIT);\n }\n }\n\n getAdInsertionDebugLog(): ReadonlyArray<{\n timestampMs: number;\n event: string;\n segmentName: string;\n offsetSeconds?: number;\n updatedAt?: string;\n detail?: string;\n }> {\n return this.adInsertionDebugHistory.slice();\n }\n\n getDebugLogs(): ReadonlyArray<{\n timestampMs: number;\n level: DebugLogLevel;\n category: string;\n message: string;\n details?: Record<string, unknown>;\n }> {\n return this.debugLogEntries.slice();\n }\n\n toggleMute(): void {\n if (this.adLayer.isAdPlaying()) {\n const isAdCurrentlyMuted = this.adLayer.getAdVolume() === 0;\n if (isAdCurrentlyMuted) {\n const savedVolume = this.adLayer.getOriginalVolume() || 1;\n this.adLayer.setAdVolume(savedVolume);\n this.adLayer.updateOriginalMutedState(false, savedVolume);\n } else {\n const currentAdVolume = this.adLayer.getAdVolume();\n this.adLayer.setAdVolume(0);\n this.adLayer.updateOriginalMutedState(true, currentAdVolume);\n }\n\n if (this.config.debugAdTiming) {\n console.log(\n \"[StormcloudVideoPlayer] Mute toggle during ad:\", isAdCurrentlyMuted ? \"unmuted\" : \"muted\"\n );\n }\n } else {\n this.video.muted = !this.video.muted;\n this.adLayer.updateOriginalMutedState(this.video.muted, this.video.volume);\n if (this.config.debugAdTiming) {\n console.log(\"[StormcloudVideoPlayer] Muted:\", this.video.muted);\n }\n }\n }\n\n toggleFullscreen(): Promise<void> {\n return new Promise((resolve, reject) => {\n if (!document.fullscreenElement) {\n const container = this.video.parentElement;\n if (!container) {\n reject(new Error(\"No parent container found for fullscreen\"));\n return;\n }\n container\n .requestFullscreen()\n .then(() => {\n if (this.config.debugAdTiming) {\n console.log(\"[StormcloudVideoPlayer] Entered fullscreen\");\n }\n resolve();\n })\n .catch((err) => {\n if (this.config.debugAdTiming) {\n console.error(\"[StormcloudVideoPlayer] Fullscreen error:\", err);\n }\n reject(err);\n });\n } else {\n document\n .exitFullscreen()\n .then(() => {\n if (this.config.debugAdTiming) {\n console.log(\"[StormcloudVideoPlayer] Exited fullscreen\");\n }\n resolve();\n })\n .catch((err) => {\n if (this.config.debugAdTiming) {\n console.error(\n \"[StormcloudVideoPlayer] Exit fullscreen error:\",\n err\n );\n }\n reject(err);\n });\n }\n });\n }\n\n isMuted(): boolean {\n if (this.adLayer.isAdPlaying()) {\n const adMuted = this.adLayer.getAdVolume() === 0;\n if (this.config.debugAdTiming) {\n console.log(\n \"[StormcloudVideoPlayer] isMuted() during ad playback ->\", adMuted\n );\n }\n return adMuted;\n }\n return this.video.muted;\n }\n\n setMuted(muted: boolean): void {\n const adPlaying = this.adLayer.isAdPlaying();\n\n if (adPlaying) {\n const savedVolume = this.adLayer.getOriginalVolume() || 1;\n this.adLayer.setAdVolume(muted ? 0 : savedVolume);\n this.adLayer.updateOriginalMutedState(muted, savedVolume);\n if (this.config.debugAdTiming) {\n console.log(\"[StormcloudVideoPlayer] setMuted applied to ad layer (content stays muted)\", {\n muted, savedVolume,\n });\n }\n return;\n }\n\n this.video.muted = muted;\n\n if (!this.inAdBreak) {\n this.adLayer.updateOriginalMutedState(muted, this.video.volume);\n }\n if (this.config.debugAdTiming) {\n console.log(\"[StormcloudVideoPlayer] setMuted called:\", muted);\n }\n }\n\n setVolume(volume: number): void {\n const clampedVolume = Math.max(0, Math.min(1, volume));\n const adPlaying = this.adLayer.isAdPlaying();\n\n if (adPlaying) {\n this.adLayer.setAdVolume(clampedVolume);\n const preservedVolume = clampedVolume > 0 ? clampedVolume : this.adLayer.getOriginalVolume();\n this.adLayer.updateOriginalMutedState(clampedVolume === 0, preservedVolume);\n if (this.config.debugAdTiming) {\n console.log(\"[StormcloudVideoPlayer] setVolume applied during ad\", {\n volume: clampedVolume,\n });\n }\n } else {\n this.video.volume = clampedVolume;\n this.video.muted = clampedVolume === 0;\n if (!this.inAdBreak) {\n this.adLayer.updateOriginalMutedState(clampedVolume === 0, clampedVolume);\n }\n if (this.config.debugAdTiming) {\n console.log(\"[StormcloudVideoPlayer] setVolume called:\", clampedVolume);\n }\n }\n }\n\n getVolume(): number {\n const adPlaying = this.adLayer.isAdPlaying();\n if (adPlaying) {\n return this.adLayer.getAdVolume();\n }\n return this.video.volume;\n }\n\n isFullscreen(): boolean {\n return !!document.fullscreenElement;\n }\n\n isLive(): boolean {\n return this.isLiveStream;\n }\n\n getMinHlsResolution(): { width: number; height: number } | null {\n const levels = this.hls?.levels;\n if (!levels || levels.length === 0) return null;\n\n let min: { width: number; height: number } | null = null;\n let minPixels = Infinity;\n\n for (const level of levels) {\n if (level.width && level.height) {\n const pixels = level.width * level.height;\n if (pixels < minPixels) {\n minPixels = pixels;\n min = { width: level.width, height: level.height };\n }\n }\n }\n return min;\n }\n\n getMaxHlsResolution(): { width: number; height: number } | null {\n const levels = this.hls?.levels;\n if (!levels || levels.length === 0) return null;\n\n let max: { width: number; height: number } | null = null;\n let maxPixels = 0;\n\n for (const level of levels) {\n if (level.width && level.height) {\n const pixels = level.width * level.height;\n if (pixels > maxPixels) {\n maxPixels = pixels;\n max = { width: level.width, height: level.height };\n }\n }\n }\n return max;\n }\n\n getCurrentHlsSegmentDurationMs(): number | null {\n const fallbackMs = 4000;\n\n if (this.nativeHlsMode) {\n return fallbackMs;\n }\n\n const hls = this.hls;\n if (!hls) return null;\n\n const levelCandidates = [hls.currentLevel, hls.nextLoadLevel, hls.loadLevel];\n for (const levelIndex of levelCandidates) {\n if (typeof levelIndex !== \"number\" || levelIndex < 0) continue;\n const details = hls.levels?.[levelIndex]?.details as\n | { targetduration?: number; partTarget?: number }\n | undefined;\n if (!details) continue;\n\n const targetDurationSec =\n typeof details.partTarget === \"number\" && details.partTarget > 0\n ? details.partTarget\n : typeof details.targetduration === \"number\" && details.targetduration > 0\n ? details.targetduration\n : undefined;\n\n if (targetDurationSec !== undefined) {\n return Math.max(800, Math.floor(targetDurationSec * 1000));\n }\n }\n\n return fallbackMs;\n }\n\n get videoElement(): HTMLVideoElement {\n return this.video;\n }\n\n resize(): void {\n if (this.config.debugAdTiming) {\n console.log(\"[StormcloudVideoPlayer] Resizing player\");\n }\n\n if (this.adLayer && this.adLayer.isAdPlaying()) {\n const width = this.video.clientWidth || 640;\n const height = this.video.clientHeight || 480;\n\n if (this.config.debugAdTiming) {\n console.log(\n `[StormcloudVideoPlayer] Resizing ads manager to ${width}x${height}`\n );\n }\n\n this.adLayer.resize(width, height);\n }\n }\n\n destroy(): void {\n this.stopAdInsertionPolling();\n this.clearAdInsertionOffsetTimer();\n this.stopContinuousFetching();\n this.stopFillerBreakTimer();\n this.clearAdStopTimer();\n this.clearAdFailsafeTimer();\n this.clearAdRequestWatchdog();\n this.clearPendingAdBreak();\n \n if (this.fillerVideo) {\n this.fillerVideo.pause();\n if (this.fillerVideo.parentElement) {\n this.fillerVideo.parentElement.removeChild(this.fillerVideo);\n }\n this.fillerVideo = undefined;\n }\n \n if (this.timeUpdateHandler) {\n this.video.removeEventListener(\"timeupdate\", this.timeUpdateHandler);\n delete this.timeUpdateHandler;\n }\n if (this.emptiedHandler) {\n this.video.removeEventListener(\"emptied\", this.emptiedHandler);\n delete this.emptiedHandler;\n }\n \n if (this.heartbeatInterval) {\n clearInterval(this.heartbeatInterval);\n this.heartbeatInterval = undefined;\n }\n this.hls?.destroy();\n this.adLayer?.destroy();\n this.consecutiveFailures = 0;\n this.debugLogEntries = [];\n this.adInsertionDebugHistory = [];\n }\n}\n","export interface VastMediaFile {\n url: string;\n type: string;\n width: number;\n height: number;\n bitrate?: number | undefined;\n}\n\nexport interface VastTrackingUrls {\n impression: string[];\n start: string[];\n firstQuartile: string[];\n midpoint: string[];\n thirdQuartile: string[];\n complete: string[];\n mute: string[];\n unmute: string[];\n pause: string[];\n resume: string[];\n fullscreen: string[];\n exitFullscreen: string[];\n skip: string[];\n error: string[];\n}\n\nexport interface VastAd {\n id: string;\n title: string;\n duration: number;\n mediaFiles: VastMediaFile[];\n trackingUrls: VastTrackingUrls;\n clickThrough?: string | undefined;\n}\n\nexport type MediaFileFilter = \"hls-only\" | \"mp4-first\" | \"all\";\n\nfunction isHlsType(type: string): boolean {\n return type === \"application/x-mpegURL\" || type.includes(\"m3u8\");\n}\n\nfunction isMp4Type(type: string): boolean {\n return type === \"video/mp4\" || type.includes(\"mp4\");\n}\n\nexport function parseVastXml(\n xmlString: string,\n filter: MediaFileFilter = \"all\",\n logPrefix = \"[VastParser]\"\n): VastAd | null {\n try {\n const parser = new DOMParser();\n const xmlDoc = parser.parseFromString(xmlString, \"text/xml\");\n\n const parserError = xmlDoc.querySelector(\"parsererror\");\n if (parserError) {\n console.error(\n `${logPrefix} XML parsing error (malformed VAST XML):`,\n parserError.textContent\n );\n return null;\n }\n\n const adElement = xmlDoc.querySelector(\"Ad\");\n if (!adElement) {\n console.warn(`${logPrefix} No Ad element found in VAST XML`);\n return null;\n }\n\n const adId = adElement.getAttribute(\"id\") || \"unknown\";\n const title = xmlDoc.querySelector(\"AdTitle\")?.textContent || \"Ad\";\n\n const isNoAdAvailable =\n adId === \"empty\" ||\n title.toLowerCase().includes(\"no ad available\") ||\n title.toLowerCase() === \"no ad available\";\n\n const durationText =\n xmlDoc.querySelector(\"Duration\")?.textContent || \"00:00:30\";\n const durationParts = durationText.split(\":\");\n const duration =\n parseInt(durationParts[0] || \"0\", 10) * 3600 +\n parseInt(durationParts[1] || \"0\", 10) * 60 +\n Math.round(parseFloat(durationParts[2] || \"0\"));\n\n const mediaFileElements = xmlDoc.querySelectorAll(\"MediaFile\");\n const mediaFiles: VastMediaFile[] = [];\n\n console.log(\n `${logPrefix} Found ${mediaFileElements.length} MediaFile element(s) in VAST XML`\n );\n\n mediaFileElements.forEach((mf, index) => {\n const type = mf.getAttribute(\"type\") || \"\";\n const url = mf.textContent?.trim() || \"\";\n const width = mf.getAttribute(\"width\") || \"\";\n const height = mf.getAttribute(\"height\") || \"\";\n\n console.log(\n `${logPrefix} MediaFile ${index}: type=\"${type}\", url=\"${url.substring(0, 80)}...\", width=\"${width}\", height=\"${height}\"`\n );\n\n if (!url) {\n console.warn(`${logPrefix} MediaFile ${index} has empty URL`);\n return;\n }\n\n const isHls = isHlsType(type);\n const isMp4 = isMp4Type(type);\n\n let accepted = false;\n if (filter === \"hls-only\") {\n accepted = isHls;\n } else if (filter === \"mp4-first\") {\n accepted = isMp4 || isHls;\n } else {\n accepted = true;\n }\n\n if (!accepted) {\n console.log(\n `${logPrefix} MediaFile ${index} ignored (type=\"${type}\" not accepted by filter \"${filter}\")`\n );\n return;\n }\n\n const bitrateAttr = mf.getAttribute(\"bitrate\");\n const bitrateValue = bitrateAttr ? parseInt(bitrateAttr, 10) : undefined;\n\n mediaFiles.push({\n url,\n type,\n width: parseInt(width || \"1920\", 10),\n height: parseInt(height || \"1080\", 10),\n bitrate: bitrateValue && bitrateValue > 0 ? bitrateValue : undefined,\n });\n\n console.log(`${logPrefix} Added MediaFile: type=\"${type}\" url=\"${url.substring(0, 80)}...\"`);\n });\n\n if (filter === \"mp4-first\" && mediaFiles.length > 1) {\n mediaFiles.sort((a, b) => {\n const aIsMp4 = isMp4Type(a.type) ? 0 : 1;\n const bIsMp4 = isMp4Type(b.type) ? 0 : 1;\n return aIsMp4 - bIsMp4;\n });\n }\n\n if (mediaFiles.length === 0) {\n if (isNoAdAvailable) {\n console.warn(\n `${logPrefix} No ads available (VAST response indicates no ads)`\n );\n } else {\n console.warn(`${logPrefix} No compatible media files found in VAST XML`);\n }\n return null;\n }\n\n const trackingUrls: VastTrackingUrls = {\n impression: [],\n start: [],\n firstQuartile: [],\n midpoint: [],\n thirdQuartile: [],\n complete: [],\n mute: [],\n unmute: [],\n pause: [],\n resume: [],\n fullscreen: [],\n exitFullscreen: [],\n skip: [],\n error: [],\n };\n\n xmlDoc.querySelectorAll(\"Impression\").forEach((el) => {\n const url = el.textContent?.trim();\n if (url) trackingUrls.impression.push(url);\n });\n\n xmlDoc.querySelectorAll(\"Tracking\").forEach((el) => {\n const event = el.getAttribute(\"event\");\n const url = el.textContent?.trim();\n if (event && url) {\n const eventKey = event as keyof VastTrackingUrls;\n if (trackingUrls[eventKey]) {\n trackingUrls[eventKey].push(url);\n }\n }\n });\n\n const clickThrough = xmlDoc\n .querySelector(\"ClickThrough\")\n ?.textContent?.trim();\n\n return {\n id: adId,\n title,\n duration,\n mediaFiles,\n trackingUrls,\n clickThrough,\n };\n } catch (error) {\n console.error(`${logPrefix} Error parsing VAST XML:`, error);\n return null;\n }\n}\n\nexport async function fetchAndParseVastAd(\n vastTagUrl: string,\n filter: MediaFileFilter = \"all\",\n logPrefix = \"[VastParser]\"\n): Promise<VastAd | null> {\n const response = await fetch(vastTagUrl, {\n mode: \"cors\",\n credentials: \"include\",\n headers: {\n Accept: \"application/xml, text/xml, */*\",\n },\n referrerPolicy: \"no-referrer-when-downgrade\",\n });\n if (!response.ok) {\n throw new Error(`Failed to fetch VAST: ${response.statusText}`);\n }\n\n const vastXml = await response.text();\n console.log(`${logPrefix} VAST XML received`);\n console.log(\n `${logPrefix} VAST XML content (first 2000 chars):`,\n vastXml.substring(0, 2000)\n );\n\n return parseVastXml(vastXml, filter, logPrefix);\n}\n\nexport function createEmptyTrackingState() {\n return {\n impression: false,\n start: false,\n firstQuartile: false,\n midpoint: false,\n thirdQuartile: false,\n complete: false,\n };\n}\n\nasync function firePixelWithRetry(\n url: string,\n retries = 2,\n delayMs = 500,\n logPrefix = \"[VastParser]\"\n): Promise<void> {\n for (let attempt = 0; attempt <= retries; attempt++) {\n try {\n await fetch(url, {\n method: \"GET\",\n mode: \"no-cors\",\n cache: \"no-cache\",\n keepalive: true,\n });\n return;\n } catch {\n if (attempt < retries) {\n await new Promise((r) => setTimeout(r, delayMs * Math.pow(2, attempt)));\n } else {\n console.warn(`${logPrefix} Tracking pixel failed after ${retries + 1} attempts: ${url}`);\n }\n }\n }\n}\n\nexport function fireTrackingPixels(\n urls: string[],\n sessionId?: string,\n logPrefix = \"[VastParser]\"\n): void {\n if (!urls || urls.length === 0) return;\n\n urls.forEach((url) => {\n try {\n let trackingUrl = url;\n\n if (sessionId) {\n trackingUrl = `${trackingUrl}${\n trackingUrl.includes(\"?\") ? \"&\" : \"?\"\n }session_id=${sessionId}`;\n }\n\n if (typeof fetch !== \"undefined\") {\n firePixelWithRetry(trackingUrl, 2, 500, logPrefix).catch(() => {});\n } else {\n const img = new Image(1, 1);\n img.onerror = () => {};\n img.src = trackingUrl;\n }\n\n console.log(`${logPrefix} Fired tracking pixel: ${trackingUrl}`);\n } catch (error) {\n console.warn(`${logPrefix} Error firing tracking pixel:`, error);\n }\n });\n}\n","import type { AdController, AdBreakContext } from \"../types\";\nimport { fireTrackingPixels as fireTrackingPixelsShared } from \"./vastParser\";\n\ninterface VastMediaFile {\n url: string;\n type: string;\n width: number;\n height: number;\n bitrate?: number | undefined;\n}\n\nconst SUPPORTED_VIDEO_EXTENSIONS = ['.mp4', '.webm', '.ogg', '.m3u8', '.ts'];\nconst UNSUPPORTED_VIDEO_EXTENSIONS = ['.flv', '.f4v', '.swf', '.wmv', '.avi', '.mov', '.mkv'];\nconst REQUEST_TIMEOUT_MS = 5000;\nconst REQUEST_MAX_RETRIES = 3;\nconst REQUEST_RETRY_BACKOFF_MS = 1500;\nconst AD_LAYER_Z_INDEX = \"30\";\nconst COUNTDOWN_Z_INDEX = \"31\";\nconst STALL_TIMEOUT_MS = 8000;\n\nfunction getFileExtension(url: string): string {\n try {\n const pathname = new URL(url, 'http://dummy').pathname;\n const lastDot = pathname.lastIndexOf('.');\n if (lastDot === -1) return '';\n return pathname.slice(lastDot).toLowerCase();\n } catch {\n const lastDot = url.lastIndexOf('.');\n if (lastDot === -1) return '';\n const ext = url.slice(lastDot).split(/[?#]/)[0];\n return (ext || '').toLowerCase();\n }\n}\n\nfunction isUnsupportedFormat(url: string): boolean {\n const ext = getFileExtension(url);\n return UNSUPPORTED_VIDEO_EXTENSIONS.indexOf(ext) !== -1;\n}\n\nfunction replaceFlvExtension(url: string): string {\n const ext = getFileExtension(url);\n if (ext === '.flv') {\n return url.replace(/\\.flv(\\?|$)/i, '.mp4$1');\n }\n return url;\n}\n\nfunction isSupportedFormat(url: string, mimeType: string): boolean {\n if (isUnsupportedFormat(url)) {\n return false;\n }\n \n const ext = getFileExtension(url);\n \n if (SUPPORTED_VIDEO_EXTENSIONS.indexOf(ext) !== -1) {\n return true;\n }\n \n if (ext === '' || ext === '.') {\n return mimeType.includes('video/mp4') || \n mimeType.includes('video/webm') || \n mimeType.includes('m3u8') ||\n mimeType.includes('application/x-mpegurl');\n }\n \n return false;\n}\n\ninterface VastTrackingUrls {\n impression: string[];\n start: string[];\n firstQuartile: string[];\n midpoint: string[];\n thirdQuartile: string[];\n complete: string[];\n mute: string[];\n unmute: string[];\n pause: string[];\n resume: string[];\n error: string[];\n}\n\ninterface VastAd {\n id: string;\n title: string;\n duration: number;\n mediaFiles: VastMediaFile[];\n trackingUrls: VastTrackingUrls;\n clickThrough?: string | undefined;\n}\n\nexport interface AdStormPlayerOptions {\n licenseKey: string;\n debug?: boolean;\n channelId?: number;\n}\n\nexport interface AdStormLayerOptionsUpdate {\n continueLiveStreamDuringAds?: boolean;\n mainHlsInstance?: unknown;\n}\n\nexport interface AdStormAdLayer extends AdController {\n requestAds: (duration?: string) => Promise<void>;\n updateOptions: (opts: AdStormLayerOptionsUpdate) => void;\n playAd: (requestContext?: unknown) => Promise<void>;\n preloadAd: (arg1: unknown, arg2?: unknown) => Promise<void>;\n playPreloaded: (token: string) => Promise<void>;\n hasPreloaded: (token: string) => boolean;\n cancelPreload: (token: string) => void;\n}\n\nexport function createAdStormPlayer(\n contentVideo: HTMLVideoElement,\n options: AdStormPlayerOptions\n): AdStormAdLayer {\n const { licenseKey, debug = false, channelId } = options;\n \n let adPlaying = false;\n let originalMutedState = false;\n let originalVolume = Math.max(0, Math.min(1, contentVideo.volume || 1));\n const listeners = new Map<string, Set<(payload?: any) => void>>();\n \n let adVideoElement: HTMLVideoElement | undefined;\n let adContainerEl: HTMLDivElement | undefined;\n let adCountdownEl: HTMLDivElement | undefined;\n let currentAd: VastAd | undefined;\n let destroyed = false;\n let tornDown = false;\n let continueLiveStreamDuringAds = false;\n let sessionId: string | undefined;\n let adStallTimerId: ReturnType<typeof setTimeout> | undefined;\n let adCountdownTimerId: ReturnType<typeof setInterval> | undefined;\n let adHideTimerId: ReturnType<typeof setTimeout> | undefined;\n let lastCountdownSecond = -1;\n let adListenersBound = false;\n let parentPositionOverridden = false;\n\n const adHandlers = {\n timeupdate: () => {\n if (!currentAd || !adVideoElement || destroyed || tornDown) return;\n const progress = adVideoElement.currentTime / currentAd.duration;\n\n if (progress >= 0.25 && !trackingFired.firstQuartile) {\n trackingFired.firstQuartile = true;\n fireTrackingPixels(currentAd.trackingUrls.firstQuartile);\n }\n if (progress >= 0.5 && !trackingFired.midpoint) {\n trackingFired.midpoint = true;\n fireTrackingPixels(currentAd.trackingUrls.midpoint);\n }\n if (progress >= 0.75 && !trackingFired.thirdQuartile) {\n trackingFired.thirdQuartile = true;\n fireTrackingPixels(currentAd.trackingUrls.thirdQuartile);\n }\n updateAdCountdown();\n },\n playing: () => {\n clearAdStallTimer();\n if (!currentAd || trackingFired.start || destroyed || tornDown) return;\n trackingFired.start = true;\n fireTrackingPixels(currentAd.trackingUrls.start);\n startAdCountdown();\n log(\"Ad started playing\");\n },\n ended: () => {\n if (!currentAd || trackingFired.complete || destroyed || tornDown) return;\n trackingFired.complete = true;\n fireTrackingPixels(currentAd.trackingUrls.complete);\n log(\"Ad completed\");\n handleAdComplete();\n },\n error: (e: Event) => {\n if (destroyed || tornDown) return;\n console.error(\"[AdStormPlayer] Ad video error:\", e);\n if (currentAd) fireTrackingPixels(currentAd.trackingUrls.error);\n handleAdError();\n },\n waiting: () => {\n clearAdStallTimer();\n adStallTimerId = setTimeout(() => {\n adStallTimerId = undefined;\n if (!adPlaying || destroyed || tornDown) return;\n console.warn(\"[AdStormPlayer] Ad playback stalled too long\");\n handleAdError();\n }, STALL_TIMEOUT_MS);\n },\n volumechange: () => {\n if (!currentAd || !adVideoElement || destroyed || tornDown) return;\n if (adVideoElement.muted || adVideoElement.volume <= 0) {\n fireTrackingPixels(currentAd.trackingUrls.mute);\n } else {\n fireTrackingPixels(currentAd.trackingUrls.unmute);\n }\n },\n pause: () => {\n if (!currentAd || !adVideoElement || destroyed || tornDown) return;\n if (!adVideoElement.ended) {\n fireTrackingPixels(currentAd.trackingUrls.pause);\n }\n },\n play: () => {\n if (!currentAd || !adVideoElement || destroyed || tornDown) return;\n if (adVideoElement.currentTime > 0) {\n fireTrackingPixels(currentAd.trackingUrls.resume);\n }\n },\n };\n \n let trackingFired = {\n impression: false,\n start: false,\n firstQuartile: false,\n midpoint: false,\n thirdQuartile: false,\n complete: false,\n };\n const preloadSlots = new Map<string, { ad: VastAd }>();\n\n function log(...args: any[]): void {\n if (debug) {\n console.log(\"[AdStormPlayer]\", ...args);\n }\n }\n\n function emit(event: string, payload?: any): void {\n const set = listeners.get(event);\n if (!set) return;\n for (const fn of Array.from(set)) {\n try {\n fn(payload);\n } catch (error) {\n console.warn(`[AdStormPlayer] Error in event listener for ${event}:`, error);\n }\n }\n }\n\n function fireTrackingPixels(urls: string[]): void {\n fireTrackingPixelsShared(urls, sessionId, \"[AdStormPlayer]\");\n }\n\n function clearAdStallTimer(): void {\n if (adStallTimerId) {\n clearTimeout(adStallTimerId);\n adStallTimerId = undefined;\n }\n }\n\n function clearAdCountdownTimer(): void {\n if (adCountdownTimerId) {\n clearInterval(adCountdownTimerId);\n adCountdownTimerId = undefined;\n }\n lastCountdownSecond = -1;\n }\n\n function updateAdCountdown(): void {\n if (!adCountdownEl || !adVideoElement || !currentAd || !adPlaying) return;\n const remainingSec = Math.max(\n 0,\n Math.ceil((currentAd.duration || 0) - adVideoElement.currentTime)\n );\n if (remainingSec === lastCountdownSecond) return;\n lastCountdownSecond = remainingSec;\n adCountdownEl.textContent = `Ad ${remainingSec}s`;\n emit(\"ad_countdown\", {\n remainingSec,\n durationSec: currentAd.duration,\n currentTimeSec: adVideoElement.currentTime,\n });\n }\n\n function startAdCountdown(): void {\n clearAdCountdownTimer();\n updateAdCountdown();\n adCountdownTimerId = setInterval(updateAdCountdown, 250);\n }\n\n function generateSessionId(): string {\n return `adstorm-${Date.now()}-${Math.random().toString(36).slice(2, 10)}`;\n }\n\n function bindAdEventListeners(): void {\n if (!adVideoElement || adListenersBound) return;\n adVideoElement.addEventListener(\"timeupdate\", adHandlers.timeupdate);\n adVideoElement.addEventListener(\"playing\", adHandlers.playing);\n adVideoElement.addEventListener(\"ended\", adHandlers.ended);\n adVideoElement.addEventListener(\"error\", adHandlers.error);\n adVideoElement.addEventListener(\"waiting\", adHandlers.waiting);\n adVideoElement.addEventListener(\"volumechange\", adHandlers.volumechange);\n adVideoElement.addEventListener(\"pause\", adHandlers.pause);\n adVideoElement.addEventListener(\"play\", adHandlers.play);\n adListenersBound = true;\n }\n\n function unbindAdEventListeners(): void {\n if (!adVideoElement || !adListenersBound) return;\n adVideoElement.removeEventListener(\"timeupdate\", adHandlers.timeupdate);\n adVideoElement.removeEventListener(\"playing\", adHandlers.playing);\n adVideoElement.removeEventListener(\"ended\", adHandlers.ended);\n adVideoElement.removeEventListener(\"error\", adHandlers.error);\n adVideoElement.removeEventListener(\"waiting\", adHandlers.waiting);\n adVideoElement.removeEventListener(\"volumechange\", adHandlers.volumechange);\n adVideoElement.removeEventListener(\"pause\", adHandlers.pause);\n adVideoElement.removeEventListener(\"play\", adHandlers.play);\n adListenersBound = false;\n }\n\n function teardownCurrentPlayback(): void {\n unbindAdEventListeners();\n clearAdStallTimer();\n clearAdCountdownTimer();\n if (!adVideoElement) return;\n adVideoElement.pause();\n adVideoElement.removeAttribute(\"src\");\n adVideoElement.load();\n }\n\n function buildVastUrl(durationSeconds: number): string {\n const baseUrl = `https://adstorm.co/api-adstorm-dev/adstorm/nab/vast/pod`;\n const params = new URLSearchParams();\n if (channelId != null) {\n params.set(\"channel_id\", String(channelId));\n }\n params.set(\"duration\", String(Math.ceil(durationSeconds)));\n return `${baseUrl}?${params.toString()}`;\n }\n\n function parseVastXml(xmlString: string): VastAd[] {\n const ads: VastAd[] = [];\n \n try {\n const parser = new DOMParser();\n const xmlDoc = parser.parseFromString(xmlString, \"text/xml\");\n \n const parserError = xmlDoc.querySelector(\"parsererror\");\n if (parserError) {\n console.error(\"[AdStormPlayer] XML parsing error:\", parserError.textContent);\n return [];\n }\n \n const adElements = xmlDoc.querySelectorAll(\"Ad\");\n \n adElements.forEach((adElement) => {\n const adId = adElement.getAttribute(\"id\") || \"unknown\";\n const title = adElement.querySelector(\"AdTitle\")?.textContent || \"Ad\";\n \n const durationText = adElement.querySelector(\"Duration\")?.textContent || \"00:00:30\";\n const durationParts = durationText.split(\":\");\n const duration =\n parseInt(durationParts[0] || \"0\", 10) * 3600 +\n parseInt(durationParts[1] || \"0\", 10) * 60 +\n parseFloat(durationParts[2] || \"0\");\n \n const mediaFileElements = adElement.querySelectorAll(\"MediaFile\");\n const mediaFiles: VastMediaFile[] = [];\n \n mediaFileElements.forEach((mf) => {\n const type = mf.getAttribute(\"type\") || \"\";\n let url = mf.textContent?.trim() || \"\";\n const width = parseInt(mf.getAttribute(\"width\") || \"1920\", 10);\n const height = parseInt(mf.getAttribute(\"height\") || \"1080\", 10);\n const bitrate = mf.getAttribute(\"bitrate\") \n ? parseInt(mf.getAttribute(\"bitrate\")!, 10) \n : undefined;\n \n if (!url) {\n log(`Skipping empty MediaFile URL`);\n return;\n }\n \n const originalUrl = url;\n url = replaceFlvExtension(url);\n if (url !== originalUrl) {\n log(`Converted FLV to MP4: ${originalUrl} -> ${url}`);\n }\n \n if (isUnsupportedFormat(url)) {\n const ext = getFileExtension(url);\n log(`Skipping unsupported format: ${url} (extension: ${ext}, declared type: ${type})`);\n return;\n }\n \n if (isSupportedFormat(url, type)) {\n mediaFiles.push({ url, type, width, height, bitrate });\n log(`Found media file: ${url} (${type}, ${width}x${height})`);\n } else {\n log(`Skipping incompatible media file: ${url} (type: ${type})`);\n }\n });\n \n if (mediaFiles.length === 0) {\n log(\"No valid media files found in ad:\", adId);\n return;\n }\n \n const trackingUrls: VastTrackingUrls = {\n impression: [],\n start: [],\n firstQuartile: [],\n midpoint: [],\n thirdQuartile: [],\n complete: [],\n mute: [],\n unmute: [],\n pause: [],\n resume: [],\n error: [],\n };\n \n adElement.querySelectorAll(\"Impression\").forEach((el) => {\n const url = el.textContent?.trim();\n if (url) trackingUrls.impression.push(url);\n });\n \n adElement.querySelectorAll(\"Tracking\").forEach((el) => {\n const event = el.getAttribute(\"event\");\n const url = el.textContent?.trim();\n if (event && url) {\n const eventKey = event as keyof VastTrackingUrls;\n if (trackingUrls[eventKey]) {\n trackingUrls[eventKey].push(url);\n }\n }\n });\n \n const clickThrough = adElement.querySelector(\"ClickThrough\")?.textContent?.trim();\n \n ads.push({\n id: adId,\n title,\n duration,\n mediaFiles,\n trackingUrls,\n clickThrough,\n });\n \n log(`Parsed ad: ${title}, duration: ${duration}s, media files: ${mediaFiles.length}`);\n });\n \n } catch (error) {\n console.error(\"[AdStormPlayer] Error parsing VAST XML:\", error);\n }\n \n return ads;\n }\n\n function selectBestMediaFile(mediaFiles: VastMediaFile[]): VastMediaFile | null {\n if (mediaFiles.length === 0) return null;\n if (mediaFiles.length === 1) return mediaFiles[0]!;\n \n const mp4Files = mediaFiles.filter(mf => mf.type.includes(\"video/mp4\"));\n const candidates = mp4Files.length > 0 ? mp4Files : mediaFiles;\n \n const targetWidth = contentVideo.videoWidth || 1280;\n const targetHeight = contentVideo.videoHeight || 720;\n \n candidates.sort((a, b) => {\n const diffA = Math.abs(a.width - targetWidth) + Math.abs(a.height - targetHeight);\n const diffB = Math.abs(b.width - targetWidth) + Math.abs(b.height - targetHeight);\n return diffA - diffB;\n });\n \n return candidates[0] || null;\n }\n\n function createAdVideoElement(): HTMLVideoElement {\n const video = document.createElement(\"video\");\n video.style.position = \"absolute\";\n video.style.left = \"0\";\n video.style.top = \"0\";\n video.style.width = \"100%\";\n video.style.height = \"100%\";\n video.style.objectFit = \"contain\";\n video.style.backgroundColor = \"#000\";\n video.style.zIndex = \"1\";\n video.playsInline = true;\n video.preload = \"auto\";\n video.muted = originalMutedState;\n video.volume = originalMutedState ? 0 : originalVolume;\n \n return video;\n }\n\n function setAdPlayingFlag(isPlaying: boolean): void {\n if (isPlaying) {\n contentVideo.dataset.stormcloudAdPlaying = \"true\";\n } else {\n delete contentVideo.dataset.stormcloudAdPlaying;\n }\n }\n\n function setupAdEventListeners(): void {\n bindAdEventListeners();\n }\n\n function handleAdComplete(): void {\n if (destroyed || tornDown) return;\n log(\"Handling ad completion\");\n adPlaying = false;\n setAdPlayingFlag(false);\n clearAdStallTimer();\n clearAdCountdownTimer();\n \n if (adContainerEl) {\n adContainerEl.style.opacity = \"0\";\n adHideTimerId = setTimeout(() => {\n if (adContainerEl) {\n adContainerEl.style.display = \"none\";\n adContainerEl.style.pointerEvents = \"none\";\n }\n }, 300);\n }\n \n contentVideo.style.visibility = \"visible\";\n contentVideo.style.opacity = \"1\";\n contentVideo.muted = originalMutedState;\n contentVideo.volume = originalVolume;\n currentAd = undefined;\n \n emit(\"content_resume\");\n emit(\"all_ads_completed\");\n }\n\n function handleAdError(): void {\n if (destroyed || tornDown) return;\n log(\"Handling ad error\");\n if (!adPlaying) return;\n adPlaying = false;\n setAdPlayingFlag(false);\n clearAdStallTimer();\n clearAdCountdownTimer();\n \n contentVideo.muted = originalMutedState;\n contentVideo.volume = originalVolume;\n contentVideo.style.visibility = \"visible\";\n contentVideo.style.opacity = \"1\";\n \n if (adContainerEl) {\n adContainerEl.style.display = \"none\";\n adContainerEl.style.pointerEvents = \"none\";\n }\n \n currentAd = undefined;\n emit(\"ad_error\");\n emit(\"content_resume\");\n }\n\n async function fetchVastOnce(durationSeconds: number): Promise<VastAd[]> {\n const vastUrl = buildVastUrl(durationSeconds);\n log(\"Fetching VAST from:\", vastUrl);\n\n const controller =\n typeof AbortController !== \"undefined\" ? new AbortController() : null;\n const timeoutId = setTimeout(() => controller?.abort(), REQUEST_TIMEOUT_MS);\n\n try {\n const requestInit: RequestInit = {\n method: \"GET\",\n mode: \"cors\",\n credentials: \"omit\",\n headers: {\n Accept: \"application/xml, text/xml, */*\",\n },\n referrerPolicy: \"no-referrer-when-downgrade\",\n };\n if (controller) {\n requestInit.signal = controller.signal;\n }\n\n const response = await fetch(vastUrl, requestInit);\n\n if (!response.ok) {\n throw new Error(`Failed to fetch VAST: ${response.status} ${response.statusText}`);\n }\n\n const xmlText = await response.text();\n log(\"VAST response received, length:\", xmlText.length);\n return parseVastXml(xmlText);\n } finally {\n clearTimeout(timeoutId);\n }\n }\n\n async function fetchVast(durationSeconds: number): Promise<VastAd[]> {\n let lastError: unknown;\n for (let attempt = 1; attempt <= REQUEST_MAX_RETRIES; attempt++) {\n try {\n const ads = await fetchVastOnce(durationSeconds);\n if (ads.length > 0) return ads;\n log(`No ad returned from VAST on attempt ${attempt}/${REQUEST_MAX_RETRIES}`);\n } catch (error: any) {\n lastError = error;\n if (error?.name === \"AbortError\") {\n console.warn(\n `[AdStormPlayer] VAST request timed out (${REQUEST_TIMEOUT_MS}ms), attempt ${attempt}/${REQUEST_MAX_RETRIES}`\n );\n } else {\n console.warn(`[AdStormPlayer] VAST request failed on attempt ${attempt}/${REQUEST_MAX_RETRIES}:`, error);\n }\n }\n\n if (attempt < REQUEST_MAX_RETRIES) {\n const delay = REQUEST_RETRY_BACKOFF_MS * attempt;\n await new Promise((resolve) => setTimeout(resolve, delay));\n }\n }\n\n if (lastError instanceof Error) {\n throw lastError;\n }\n return [];\n }\n\n function getDurationSecondsFromContext(requestContext?: unknown): number {\n if (!requestContext || typeof requestContext !== \"object\") {\n return 30;\n }\n const ctx = requestContext as AdBreakContext;\n const value = ctx.remainingBreakSec ?? ctx.breakDurationSec;\n if (typeof value !== \"number\" || Number.isNaN(value)) {\n return 30;\n }\n return Math.max(1, Math.ceil(value));\n }\n\n async function requestAdFromApi(requestContext?: unknown): Promise<VastAd | null> {\n const durationSeconds = getDurationSecondsFromContext(requestContext);\n const ads = await fetchVast(durationSeconds);\n return ads[0] || null;\n }\n\n function assignCurrentAd(ad: VastAd): void {\n currentAd = ad;\n sessionId = generateSessionId();\n trackingFired = {\n impression: false,\n start: false,\n firstQuartile: false,\n midpoint: false,\n thirdQuartile: false,\n complete: false,\n };\n fireTrackingPixels(currentAd.trackingUrls.impression);\n trackingFired.impression = true;\n emit(\"ad_impression\");\n }\n\n return {\n initialize() {\n log(\"Initializing\");\n \n if (!adContainerEl) {\n const parent = contentVideo.parentElement;\n if (parent) {\n const computed = window.getComputedStyle(parent).position;\n if (computed === \"static\") {\n parent.style.position = \"relative\";\n parentPositionOverridden = true;\n }\n }\n\n const container = document.createElement(\"div\");\n container.style.position = \"absolute\";\n container.style.left = \"0\";\n container.style.top = \"0\";\n container.style.right = \"0\";\n container.style.bottom = \"0\";\n container.style.display = \"none\";\n container.style.alignItems = \"center\";\n container.style.justifyContent = \"center\";\n container.style.pointerEvents = \"none\";\n container.style.zIndex = AD_LAYER_Z_INDEX;\n container.style.backgroundColor = \"#000\";\n container.style.transition = \"opacity 0.3s ease-in-out\";\n container.style.opacity = \"0\";\n container.style.isolation = \"isolate\";\n \n const countdown = document.createElement(\"div\");\n countdown.style.position = \"absolute\";\n countdown.style.left = \"12px\";\n countdown.style.top = \"12px\";\n countdown.style.padding = \"4px 8px\";\n countdown.style.borderRadius = \"4px\";\n countdown.style.background = \"rgba(0,0,0,0.75)\";\n countdown.style.color = \"#fff\";\n countdown.style.fontFamily = \"sans-serif\";\n countdown.style.fontSize = \"12px\";\n countdown.style.lineHeight = \"1.2\";\n countdown.style.pointerEvents = \"none\";\n countdown.style.zIndex = COUNTDOWN_Z_INDEX;\n countdown.textContent = \"Ad\";\n container.appendChild(countdown);\n\n contentVideo.parentElement?.appendChild(container);\n adContainerEl = container;\n adCountdownEl = countdown;\n }\n },\n\n async requestAds(duration?: string) {\n log(\"Requesting ads for duration:\", duration);\n \n if (adPlaying) {\n return Promise.reject(new Error(\"Ad already playing\"));\n }\n if (destroyed) {\n return Promise.reject(new Error(\"Player has been destroyed\"));\n }\n \n try {\n tornDown = false;\n let durationSeconds = 30;\n const parsed = parseInt(duration || \"\", 10);\n if (!isNaN(parsed) && parsed > 0) {\n durationSeconds = parsed;\n }\n \n const ads = await fetchVast(durationSeconds);\n \n if (ads.length === 0) {\n log(\"No ads available from VAST response\");\n emit(\"ad_error\");\n return Promise.resolve();\n }\n \n assignCurrentAd(ads[0]!);\n log(`Ad loaded: ${currentAd!.title}, duration: ${currentAd!.duration}s`);\n \n return Promise.resolve();\n } catch (error) {\n console.error(\"[AdStormPlayer] Error requesting ads:\", error);\n emit(\"ad_error\");\n return Promise.reject(error);\n }\n },\n\n async play() {\n if (!currentAd) {\n return Promise.reject(new Error(\"No ad loaded\"));\n }\n if (destroyed) {\n return Promise.reject(new Error(\"Player has been destroyed\"));\n }\n \n log(\"Starting ad playback\");\n \n try {\n tornDown = false;\n if (adHideTimerId) {\n clearTimeout(adHideTimerId);\n adHideTimerId = undefined;\n }\n\n if (!adVideoElement) {\n adVideoElement = createAdVideoElement();\n adContainerEl?.appendChild(adVideoElement);\n } else {\n teardownCurrentPlayback();\n }\n setupAdEventListeners();\n \n trackingFired = {\n impression: trackingFired.impression,\n start: false,\n firstQuartile: false,\n midpoint: false,\n thirdQuartile: false,\n complete: false,\n };\n \n contentVideo.style.transition = \"opacity 0.3s ease-in-out\";\n contentVideo.style.opacity = \"0\";\n setTimeout(() => {\n contentVideo.style.visibility = \"hidden\";\n }, 300);\n contentVideo.muted = true;\n contentVideo.volume = 0;\n \n if (!continueLiveStreamDuringAds) {\n contentVideo.pause();\n }\n \n adPlaying = true;\n setAdPlayingFlag(true);\n \n if (adVideoElement) {\n adVideoElement.volume = originalMutedState ? 0 : originalVolume;\n adVideoElement.muted = originalMutedState;\n }\n \n if (adContainerEl) {\n adContainerEl.style.display = \"flex\";\n adContainerEl.style.pointerEvents = \"auto\";\n adContainerEl.offsetHeight;\n adContainerEl.style.opacity = \"1\";\n }\n \n emit(\"content_pause\");\n \n const mediaFile = selectBestMediaFile(currentAd.mediaFiles);\n if (!mediaFile) {\n throw new Error(\"No media file available\");\n }\n \n log(\"Playing media file:\", mediaFile.url);\n adVideoElement!.src = mediaFile.url;\n adVideoElement!.load();\n \n await adVideoElement!.play();\n \n return Promise.resolve();\n } catch (error) {\n console.error(\"[AdStormPlayer] Error playing ad:\", error);\n handleAdError();\n return Promise.reject(error);\n }\n },\n\n async stop() {\n log(\"Stopping ad\");\n tornDown = true;\n adPlaying = false;\n setAdPlayingFlag(false);\n clearAdStallTimer();\n clearAdCountdownTimer();\n \n if (adContainerEl) {\n adContainerEl.style.opacity = \"0\";\n adHideTimerId = setTimeout(() => {\n if (adContainerEl) {\n adContainerEl.style.display = \"none\";\n adContainerEl.style.pointerEvents = \"none\";\n }\n }, 300);\n }\n \n teardownCurrentPlayback();\n \n contentVideo.style.visibility = \"visible\";\n contentVideo.style.opacity = \"1\";\n contentVideo.muted = originalMutedState;\n contentVideo.volume = originalVolume;\n \n currentAd = undefined;\n return Promise.resolve();\n },\n\n pause() {\n if (!adPlaying || !adVideoElement) return;\n try {\n if (!adVideoElement.paused) adVideoElement.pause();\n } catch (error) {\n console.warn(\"[AdStormPlayer] Error pausing ad:\", error);\n }\n },\n\n resume() {\n if (!adPlaying || !adVideoElement) return;\n try {\n if (adVideoElement.paused) adVideoElement.play().catch(() => {});\n } catch (error) {\n console.warn(\"[AdStormPlayer] Error resuming ad:\", error);\n }\n },\n\n destroy() {\n log(\"Destroying\");\n destroyed = true;\n tornDown = true;\n adPlaying = false;\n setAdPlayingFlag(false);\n clearAdStallTimer();\n clearAdCountdownTimer();\n if (adHideTimerId) {\n clearTimeout(adHideTimerId);\n adHideTimerId = undefined;\n }\n \n contentVideo.muted = originalMutedState;\n contentVideo.volume = originalVolume;\n contentVideo.style.visibility = \"visible\";\n contentVideo.style.opacity = \"1\";\n \n teardownCurrentPlayback();\n adVideoElement?.remove();\n adVideoElement = undefined;\n \n if (adContainerEl?.parentElement) {\n adContainerEl.parentElement.removeChild(adContainerEl);\n }\n \n adContainerEl = undefined;\n adCountdownEl = undefined;\n currentAd = undefined;\n sessionId = undefined;\n preloadSlots.clear();\n listeners.clear();\n if (parentPositionOverridden && contentVideo.parentElement) {\n contentVideo.parentElement.style.position = \"\";\n parentPositionOverridden = false;\n }\n },\n\n updateOptions(opts: AdStormLayerOptionsUpdate) {\n if (opts.continueLiveStreamDuringAds !== undefined) {\n continueLiveStreamDuringAds = opts.continueLiveStreamDuringAds;\n }\n },\n\n async playAd(requestContext?: unknown) {\n if (destroyed) return Promise.reject(new Error(\"Player has been destroyed\"));\n if (!currentAd) {\n const ad = await requestAdFromApi(requestContext);\n if (!ad) {\n emit(\"ad_error\", { message: \"No valid ad from AdStorm API\" });\n return Promise.reject(new Error(\"No valid ad from AdStorm API\"));\n }\n assignCurrentAd(ad);\n }\n return this.play();\n },\n\n async preloadAd(arg1: unknown, arg2?: unknown) {\n if (destroyed) return;\n const token =\n typeof arg1 === \"string\"\n ? arg1\n : typeof arg2 === \"string\"\n ? arg2\n : undefined;\n if (!token) return;\n\n if (currentAd) {\n preloadSlots.set(token, { ad: currentAd });\n currentAd = undefined;\n return;\n }\n\n const requestContext = typeof arg1 === \"string\" ? arg2 : arg1;\n const ad = await requestAdFromApi(requestContext);\n if (!ad) return;\n preloadSlots.set(token, { ad });\n },\n\n async playPreloaded(token: string) {\n if (destroyed) return Promise.reject(new Error(\"Player has been destroyed\"));\n const slot = preloadSlots.get(token);\n if (!slot) {\n return Promise.reject(new Error(`No preloaded ad for token ${token}`));\n }\n preloadSlots.delete(token);\n assignCurrentAd(slot.ad);\n return this.play();\n },\n\n hasPreloaded(token: string): boolean {\n return preloadSlots.has(token);\n },\n\n cancelPreload(token: string) {\n preloadSlots.delete(token);\n },\n\n isAdPlaying() {\n return adPlaying;\n },\n\n resize(width: number, height: number) {\n log(`Resizing to ${width}x${height}`);\n \n if (adContainerEl) {\n adContainerEl.style.width = `${width}px`;\n adContainerEl.style.height = `${height}px`;\n }\n \n if (adVideoElement) {\n adVideoElement.style.width = `${width}px`;\n adVideoElement.style.height = `${height}px`;\n }\n },\n\n on(event: string, listener: (payload?: any) => void) {\n if (!listeners.has(event)) listeners.set(event, new Set());\n listeners.get(event)!.add(listener);\n },\n\n off(event: string, listener: (payload?: any) => void) {\n listeners.get(event)?.delete(listener);\n },\n\n updateOriginalMutedState(muted: boolean, volume?: number) {\n const nextVolume =\n typeof volume === \"number\" && !Number.isNaN(volume)\n ? Math.max(0, Math.min(1, volume))\n : originalVolume;\n log(`updateOriginalMutedState: muted=${muted}, volume=${nextVolume}`);\n originalMutedState = muted;\n originalVolume = nextVolume;\n },\n\n getOriginalMutedState() {\n return originalMutedState;\n },\n\n getOriginalVolume() {\n return originalVolume;\n },\n\n setAdVolume(volume: number) {\n if (adVideoElement && adPlaying) {\n adVideoElement.volume = Math.max(0, Math.min(1, volume));\n adVideoElement.muted = volume === 0;\n }\n },\n\n getAdVolume(): number {\n if (adVideoElement && adPlaying) {\n return adVideoElement.volume;\n }\n return 1;\n },\n\n showPlaceholder() {\n if (!adContainerEl) {\n const parent = contentVideo.parentElement;\n if (parent) {\n const computed = window.getComputedStyle(parent).position;\n if (computed === \"static\") {\n parent.style.position = \"relative\";\n parentPositionOverridden = true;\n }\n }\n\n const container = document.createElement(\"div\");\n container.style.position = \"absolute\";\n container.style.left = \"0\";\n container.style.top = \"0\";\n container.style.right = \"0\";\n container.style.bottom = \"0\";\n container.style.display = \"none\";\n container.style.alignItems = \"center\";\n container.style.justifyContent = \"center\";\n container.style.pointerEvents = \"none\";\n container.style.zIndex = AD_LAYER_Z_INDEX;\n container.style.backgroundColor = \"#000\";\n container.style.isolation = \"isolate\";\n\n const countdown = document.createElement(\"div\");\n countdown.style.position = \"absolute\";\n countdown.style.left = \"12px\";\n countdown.style.top = \"12px\";\n countdown.style.padding = \"4px 8px\";\n countdown.style.borderRadius = \"4px\";\n countdown.style.background = \"rgba(0,0,0,0.75)\";\n countdown.style.color = \"#fff\";\n countdown.style.fontFamily = \"sans-serif\";\n countdown.style.fontSize = \"12px\";\n countdown.style.lineHeight = \"1.2\";\n countdown.style.pointerEvents = \"none\";\n countdown.style.zIndex = COUNTDOWN_Z_INDEX;\n countdown.textContent = \"Ad\";\n container.appendChild(countdown);\n \n contentVideo.parentElement?.appendChild(container);\n adContainerEl = container;\n adCountdownEl = countdown;\n }\n \n if (adContainerEl) {\n adContainerEl.style.display = \"flex\";\n adContainerEl.style.opacity = \"1\";\n adContainerEl.style.pointerEvents = \"auto\";\n }\n },\n\n hidePlaceholder() {\n if (adContainerEl) {\n adContainerEl.style.opacity = \"0\";\n setTimeout(() => {\n if (adContainerEl) {\n adContainerEl.style.display = \"none\";\n adContainerEl.style.pointerEvents = \"none\";\n }\n }, 300);\n }\n },\n };\n}\n\n","import type {\n ClientInfo,\n TrackingData,\n HeartbeatData,\n AdDetectInfo,\n AdLoadedInfo,\n AdImpressionInfo,\n} from \"../types\";\n\nlet cachedBrowserId: string | null = null;\n\nexport function getClientInfo(): ClientInfo {\n const ua = navigator.userAgent;\n const platform = navigator.platform;\n const vendor = navigator.vendor || \"\";\n const maxTouchPoints = navigator.maxTouchPoints || 0;\n const memory = (navigator as any).deviceMemory || null;\n const hardwareConcurrency = navigator.hardwareConcurrency || 1;\n\n const screenInfo = {\n width: screen?.width,\n height: screen?.height,\n availWidth: screen?.availWidth,\n availHeight: screen?.availHeight,\n orientation: (screen?.orientation as any)?.type || \"\",\n pixelDepth: screen?.pixelDepth,\n };\n\n let deviceType: \"tv\" | \"mobile\" | \"tablet\" | \"desktop\" = \"desktop\";\n let brand = \"Unknown\";\n let os = \"Unknown\";\n let model = \"\";\n let isSmartTV = false;\n let isAndroid = false;\n let isWebView = false;\n let isWebApp = false;\n\n if (ua.includes(\"Web0S\")) {\n brand = \"LG\";\n os = \"webOS\";\n isSmartTV = true;\n deviceType = \"tv\";\n const webosMatch = ua.match(/Web0S\\/([^\\s]+)/);\n model = webosMatch ? `webOS ${webosMatch[1]}` : \"webOS TV\";\n } else if (ua.includes(\"Tizen\")) {\n brand = \"Samsung\";\n os = \"Tizen\";\n isSmartTV = true;\n deviceType = \"tv\";\n const tizenMatch = ua.match(/Tizen\\/([^\\s]+)/);\n const tvMatch = ua.match(/(?:Smart-TV|SMART-TV|TV)/i) ? \"Smart TV\" : \"\";\n model = tizenMatch\n ? `Tizen ${tizenMatch[1]} ${tvMatch}`.trim()\n : \"Tizen TV\";\n } else if (ua.includes(\"Philips\")) {\n brand = \"Philips\";\n os = \"Saphi\";\n isSmartTV = true;\n deviceType = \"tv\";\n } else if (ua.includes(\"Sharp\") || ua.includes(\"AQUOS\")) {\n brand = \"Sharp\";\n os = \"Android TV\";\n isSmartTV = true;\n deviceType = \"tv\";\n } else if (\n ua.includes(\"Android\") &&\n (ua.includes(\"Sony\") || vendor.includes(\"Sony\"))\n ) {\n brand = \"Sony\";\n os = \"Android TV\";\n isSmartTV = true;\n deviceType = \"tv\";\n } else if (\n ua.includes(\"Android\") &&\n (ua.includes(\"NetCast\") || ua.includes(\"LG\"))\n ) {\n brand = \"LG\";\n os = \"Android TV\";\n isSmartTV = true;\n deviceType = \"tv\";\n } else if (ua.includes(\" Roku\") || ua.includes(\"Roku/\")) {\n brand = \"Roku\";\n os = \"Roku OS\";\n isSmartTV = true;\n deviceType = \"tv\";\n } else if (ua.includes(\"AppleTV\")) {\n brand = \"Apple\";\n os = \"tvOS\";\n isSmartTV = true;\n deviceType = \"tv\";\n }\n\n if (ua.includes(\"Android\")) {\n isAndroid = true;\n os = \"Android\";\n deviceType = /Mobile/.test(ua) ? \"mobile\" : \"tablet\";\n\n if (\n ua.includes(\"Android\") &&\n (maxTouchPoints === 0 ||\n ua.includes(\"Google TV\") ||\n ua.includes(\"XiaoMi\"))\n ) {\n deviceType = \"tv\";\n isSmartTV = true;\n brand = brand === \"Unknown\" ? \"Android TV\" : brand;\n }\n\n const androidModelMatch = ua.match(/\\(([^)]*Android[^)]*)\\)/);\n if (androidModelMatch && androidModelMatch[1]) {\n model = androidModelMatch[1];\n }\n }\n\n if (/iPad|iPhone|iPod/.test(ua)) {\n os = \"iOS\";\n deviceType = \"mobile\";\n brand = \"Apple\";\n if (navigator.maxTouchPoints > 1 && /iPad/.test(ua)) {\n deviceType = \"tablet\";\n }\n }\n\n if (!isAndroid && !isSmartTV && !/Mobile/.test(ua)) {\n if (ua.includes(\"Windows\")) {\n os = \"Windows\";\n deviceType = \"desktop\";\n } else if (ua.includes(\"Mac\") && !/iPhone/.test(ua)) {\n os = \"macOS\";\n deviceType = \"desktop\";\n if (maxTouchPoints > 1) deviceType = \"tablet\";\n } else if (ua.includes(\"Linux\")) {\n os = \"Linux\";\n deviceType = \"desktop\";\n }\n }\n\n if (brand === \"Unknown\") {\n if (vendor.includes(\"Google\") || ua.includes(\"Chrome\")) brand = \"Google\";\n if (vendor.includes(\"Apple\")) brand = \"Apple\";\n if (vendor.includes(\"Samsung\") || ua.includes(\"SM-\")) brand = \"Samsung\";\n }\n\n isWebView = /wv|WebView|Linux; U;/.test(ua);\n\n if (window?.outerHeight === 0 && window?.outerWidth === 0) {\n isWebView = true;\n }\n\n isWebApp =\n window.matchMedia(\"(display-mode: standalone)\").matches ||\n (window.navigator as any).standalone === true ||\n window.screen?.orientation?.angle !== undefined;\n\n return {\n brand,\n os,\n model: model || ua.substring(0, 50) + \"...\",\n deviceType,\n isSmartTV,\n isAndroid,\n isWebView,\n isWebApp,\n domain: window.location.hostname,\n origin: window.location.origin,\n path: window.location.pathname,\n userAgent: ua,\n vendor,\n platform,\n screen: screenInfo,\n hardwareConcurrency,\n deviceMemory: memory,\n maxTouchPoints,\n language: navigator.language,\n languages: navigator.languages?.join(\",\") || \"\",\n cookieEnabled: navigator.cookieEnabled,\n doNotTrack: navigator.doNotTrack || \"\",\n referrer: document.referrer,\n visibilityState: document.visibilityState,\n };\n}\n\nexport async function getBrowserID(clientInfo: ClientInfo): Promise<string> {\n if (cachedBrowserId) {\n return cachedBrowserId;\n }\n\n const fingerprintString = JSON.stringify(clientInfo);\n\n if (typeof crypto !== \"undefined\" && crypto.subtle && crypto.subtle.digest) {\n try {\n await crypto.subtle.digest(\"SHA-256\", new Uint8Array([1, 2, 3]));\n\n let encodedData: BufferSource;\n if (typeof TextEncoder !== \"undefined\") {\n encodedData = new TextEncoder().encode(fingerprintString);\n } else {\n const utf8 = unescape(encodeURIComponent(fingerprintString));\n const buffer = new Uint8Array(utf8.length);\n for (let i = 0; i < utf8.length; i++) {\n buffer[i] = utf8.charCodeAt(i);\n }\n encodedData = buffer;\n }\n\n const hashBuffer = await crypto.subtle.digest(\"SHA-256\", encodedData);\n const hashArray = Array.from(new Uint8Array(hashBuffer));\n const hashHex = hashArray\n .map((b) => b.toString(16).padStart(2, \"0\"))\n .join(\"\");\n cachedBrowserId = hashHex;\n return hashHex;\n } catch (error) {\n console.warn(\n \"[StormcloudVideoPlayer] crypto.subtle.digest not supported, using fallback hash\"\n );\n }\n }\n\n let hash = 0;\n for (let i = 0; i < fingerprintString.length; i++) {\n const char = fingerprintString.charCodeAt(i);\n hash = (hash << 5) - hash + char;\n hash = hash & hash;\n }\n\n const fallbackHash = Math.abs(hash).toString(16).padStart(8, \"0\");\n const timestamp = Date.now().toString(16).padStart(12, \"0\");\n const random = Math.random().toString(16).substring(2, 14).padStart(12, \"0\");\n\n cachedBrowserId = (fallbackHash + timestamp + random).padEnd(64, \"0\");\n return cachedBrowserId;\n}\n\nconst TRACK_URL =\n \"https://adstorm.co/api-adstorm-dev/adstorm/player-tracking/track\";\n\nasync function sendTrackRequest(\n licenseKey: string | undefined,\n body: Record<string, unknown>\n): Promise<void> {\n const headers: Record<string, string> = {\n \"Content-Type\": \"application/json\",\n };\n if (licenseKey) {\n headers[\"Authorization\"] = `Bearer ${licenseKey}`;\n }\n const response = await fetch(TRACK_URL, {\n method: \"POST\",\n headers,\n body: JSON.stringify(body),\n });\n if (!response.ok) {\n throw new Error(`HTTP error! status: ${response.status}`);\n }\n await response.json();\n}\n\nexport async function sendInitialTracking(licenseKey?: string): Promise<void> {\n try {\n const clientInfo = getClientInfo();\n const browserId = await getBrowserID(clientInfo);\n\n const trackingData: TrackingData = {\n browserId,\n ...clientInfo,\n };\n\n const headers: Record<string, string> = {\n \"Content-Type\": \"application/json\",\n };\n if (licenseKey) {\n headers[\"Authorization\"] = `Bearer ${licenseKey}`;\n }\n\n const response = await fetch(TRACK_URL, {\n method: \"POST\",\n headers,\n body: JSON.stringify(trackingData),\n });\n\n if (!response.ok) {\n throw new Error(`HTTP error! status: ${response.status}`);\n }\n\n await response.json();\n } catch (error) {\n console.error(\n \"[StormcloudVideoPlayer] Error sending initial tracking data:\",\n error\n );\n }\n}\n\nexport async function sendAdDetectTracking(\n licenseKey: string | undefined,\n adDetectInfo: AdDetectInfo\n): Promise<void> {\n try {\n const clientInfo = getClientInfo();\n const browserId = await getBrowserID(clientInfo);\n const trackingData: TrackingData = { browserId, ...clientInfo };\n await sendTrackRequest(licenseKey, {\n ...trackingData,\n licenseKey,\n adDetectInfo,\n });\n } catch (error) {\n console.error(\n \"[StormcloudVideoPlayer] Error sending ad detect tracking:\",\n error\n );\n }\n}\n\nexport async function sendAdLoadedTracking(\n licenseKey: string | undefined,\n adLoadedInfo: AdLoadedInfo\n): Promise<void> {\n try {\n const clientInfo = getClientInfo();\n const browserId = await getBrowserID(clientInfo);\n const trackingData: TrackingData = { browserId, ...clientInfo };\n await sendTrackRequest(licenseKey, {\n ...trackingData,\n licenseKey,\n adLoadedInfo,\n });\n } catch (error) {\n console.error(\n \"[StormcloudVideoPlayer] Error sending ad loaded tracking:\",\n error\n );\n }\n}\n\nexport async function sendAdImpressionTracking(\n licenseKey: string | undefined,\n adImpressionInfo: AdImpressionInfo\n): Promise<void> {\n try {\n const clientInfo = getClientInfo();\n const browserId = await getBrowserID(clientInfo);\n const trackingData: TrackingData = { browserId, ...clientInfo };\n await sendTrackRequest(licenseKey, {\n ...trackingData,\n licenseKey,\n adImpressionInfo,\n });\n } catch (error) {\n console.error(\n \"[StormcloudVideoPlayer] Error sending ad impression tracking:\",\n error\n );\n }\n}\n\nexport async function sendHeartbeat(licenseKey?: string): Promise<void> {\n try {\n const clientInfo = getClientInfo();\n const browserId = await getBrowserID(clientInfo);\n\n const heartbeatData: HeartbeatData = {\n browserId,\n timestamp: new Date().toISOString(),\n };\n\n const headers: Record<string, string> = {\n \"Content-Type\": \"application/json\",\n };\n if (licenseKey) {\n headers[\"Authorization\"] = `Bearer ${licenseKey}`;\n }\n\n const response = await fetch(\n \"https://adstorm.co/api-adstorm-dev/adstorm/player-tracking/heartbeat\",\n {\n method: \"POST\",\n headers,\n body: JSON.stringify(heartbeatData),\n }\n );\n\n if (!response.ok) {\n throw new Error(`HTTP error! status: ${response.status}`);\n }\n\n await response.json();\n } catch (error) {\n console.error(\"[StormcloudVideoPlayer] Error sending heartbeat:\", error);\n }\n}\n","export function polyfillURLSearchParams(): void {\n if (typeof URLSearchParams !== 'undefined') {\n return;\n }\n\n class URLSearchParamsPolyfill {\n private params: Map<string, string[]>;\n\n constructor(init?: string | URLSearchParamsPolyfill) {\n this.params = new Map();\n\n if (typeof init === 'string') {\n this.parseQueryString(init);\n } else if (init instanceof URLSearchParamsPolyfill) {\n init.forEach((value, key) => {\n this.append(key, value);\n });\n }\n }\n\n private parseQueryString(query: string): void {\n const cleanQuery = query.startsWith('?') ? query.slice(1) : query;\n if (!cleanQuery) return;\n\n cleanQuery.split('&').forEach((param) => {\n const [key, value] = param.split('=');\n if (key) {\n const decodedKey = this.safeDecodeURIComponent(key);\n const decodedValue = value ? this.safeDecodeURIComponent(value) : '';\n this.append(decodedKey, decodedValue);\n }\n });\n }\n\n private safeDecodeURIComponent(str: string): string {\n try {\n return decodeURIComponent(str.replace(/\\+/g, ' '));\n } catch (e) {\n return str;\n }\n }\n\n append(name: string, value: string): void {\n const values = this.params.get(name) || [];\n values.push(String(value));\n this.params.set(name, values);\n }\n\n delete(name: string): void {\n this.params.delete(name);\n }\n\n get(name: string): string | null {\n const values = this.params.get(name);\n return values && values.length > 0 && values[0] !== undefined ? values[0] : null;\n }\n\n getAll(name: string): string[] {\n return this.params.get(name) || [];\n }\n\n has(name: string): boolean {\n return this.params.has(name);\n }\n\n set(name: string, value: string): void {\n this.params.set(name, [String(value)]);\n }\n\n forEach(callback: (value: string, key: string, parent: URLSearchParamsPolyfill) => void): void {\n this.params.forEach((values, key) => {\n values.forEach((value) => {\n callback(value, key, this);\n });\n });\n }\n\n toString(): string {\n const parts: string[] = [];\n this.params.forEach((values, key) => {\n values.forEach((value) => {\n parts.push(`${encodeURIComponent(key)}=${encodeURIComponent(value)}`);\n });\n });\n return parts.join('&');\n }\n }\n\n // @ts-ignore\n window.URLSearchParams = URLSearchParamsPolyfill;\n}\n\nexport function polyfillTextEncoder(): void {\n if (typeof TextEncoder !== 'undefined') {\n return;\n }\n\n class TextEncoderPolyfill {\n encoding = 'utf-8';\n\n encode(str: string): Uint8Array {\n const utf8: number[] = [];\n for (let i = 0; i < str.length; i++) {\n let charcode = str.charCodeAt(i);\n if (charcode < 0x80) {\n utf8.push(charcode);\n } else if (charcode < 0x800) {\n utf8.push(0xc0 | (charcode >> 6), 0x80 | (charcode & 0x3f));\n } else if (charcode < 0xd800 || charcode >= 0xe000) {\n utf8.push(\n 0xe0 | (charcode >> 12),\n 0x80 | ((charcode >> 6) & 0x3f),\n 0x80 | (charcode & 0x3f)\n );\n } else {\n i++;\n charcode = 0x10000 + (((charcode & 0x3ff) << 10) | (str.charCodeAt(i) & 0x3ff));\n utf8.push(\n 0xf0 | (charcode >> 18),\n 0x80 | ((charcode >> 12) & 0x3f),\n 0x80 | ((charcode >> 6) & 0x3f),\n 0x80 | (charcode & 0x3f)\n );\n }\n }\n return new Uint8Array(utf8);\n }\n }\n\n // @ts-ignore\n window.TextEncoder = TextEncoderPolyfill;\n}\n\nexport function polyfillPromiseFinally(): void {\n if (typeof Promise !== 'undefined' && !Promise.prototype.finally) {\n Promise.prototype.finally = function (callback: () => void) {\n const constructor = this.constructor as PromiseConstructor;\n return this.then(\n (value) => constructor.resolve(callback()).then(() => value),\n (reason) =>\n constructor.resolve(callback()).then(() => {\n throw reason;\n })\n );\n };\n }\n}\n\nexport function polyfillObjectAssign(): void {\n if (typeof Object.assign !== 'function') {\n Object.assign = function (target: any, ...sources: any[]) {\n if (target == null) {\n throw new TypeError('Cannot convert undefined or null to object');\n }\n\n const to = Object(target);\n\n for (let i = 0; i < sources.length; i++) {\n const nextSource = sources[i];\n\n if (nextSource != null) {\n for (const nextKey in nextSource) {\n if (Object.prototype.hasOwnProperty.call(nextSource, nextKey)) {\n to[nextKey] = nextSource[nextKey];\n }\n }\n }\n }\n\n return to;\n };\n }\n}\n\nexport function polyfillArrayFrom(): void {\n if (!Array.from) {\n Array.from = function (arrayLike: any, mapFn?: any, thisArg?: any) {\n const items = Object(arrayLike);\n if (arrayLike == null) {\n throw new TypeError('Array.from requires an array-like object');\n }\n\n const len = items.length >>> 0;\n const result = new Array(len);\n\n for (let i = 0; i < len; i++) {\n if (mapFn) {\n result[i] = mapFn.call(thisArg, items[i], i);\n } else {\n result[i] = items[i];\n }\n }\n\n return result;\n };\n }\n}\n\nexport function polyfillStringStartsWith(): void {\n if (!String.prototype.startsWith) {\n String.prototype.startsWith = function (search: string, pos?: number) {\n pos = !pos || pos < 0 ? 0 : +pos;\n return this.substring(pos, pos + search.length) === search;\n };\n }\n}\n\nexport function polyfillStringEndsWith(): void {\n if (!String.prototype.endsWith) {\n String.prototype.endsWith = function (search: string, length?: number) {\n if (length === undefined || length > this.length) {\n length = this.length;\n }\n return this.substring(length - search.length, length) === search;\n };\n }\n}\n\nexport function polyfillStringIncludes(): void {\n if (!String.prototype.includes) {\n String.prototype.includes = function (search: string, start?: number) {\n if (typeof start !== 'number') {\n start = 0;\n }\n if (start + search.length > this.length) {\n return false;\n }\n return this.indexOf(search, start) !== -1;\n };\n }\n}\n\nexport function initializePolyfills(): void {\n polyfillObjectAssign();\n polyfillArrayFrom();\n polyfillStringStartsWith();\n polyfillStringEndsWith();\n polyfillStringIncludes();\n polyfillURLSearchParams();\n polyfillTextEncoder();\n polyfillPromiseFinally();\n}\n\n","interface NavigatorUAData {\n platform?: string;\n brands?: Array<{ brand: string; version: string }>;\n mobile?: boolean;\n}\n\ndeclare global {\n interface Navigator {\n userAgentData?: NavigatorUAData;\n }\n}\n\nexport interface BrowserInfo {\n name: string;\n version: string;\n majorVersion: number;\n isSmartTV: boolean;\n isLegacyTV: boolean;\n platform: string;\n supportsIMA: boolean;\n supportsModernJS: boolean;\n recommendedAdPlayer: 'ima' | 'hls';\n webOSVersion?: number | undefined;\n tizenVersion?: number | undefined;\n chromeVersion?: number | undefined;\n}\n\nfunction getChromeVersion(ua: string): number {\n const match = ua.match(/Chrome\\/(\\d+)/);\n return match && match[1] ? parseInt(match[1], 10) : 0;\n}\n\nfunction getWebKitVersion(ua: string): number {\n const match = ua.match(/AppleWebKit\\/(\\d+)/);\n return match && match[1] ? parseInt(match[1], 10) : 0;\n}\n\nfunction getPlatform(): string {\n if ('userAgentData' in navigator && navigator.userAgentData?.platform) {\n return navigator.userAgentData.platform;\n }\n\n const ua = navigator.userAgent;\n if (/Mac|iPhone|iPad|iPod/i.test(ua)) {\n return /iPhone|iPad|iPod/i.test(ua) ? 'iPhone' : 'MacIntel';\n }\n if (/Win/i.test(ua)) {\n return 'Win32';\n }\n if (/Linux/i.test(ua)) {\n return /Android/i.test(ua) ? 'Linux armv8l' : 'Linux x86_64';\n }\n if (/CrOS/i.test(ua)) {\n return 'CrOS';\n }\n\n // eslint-disable-next-line deprecation/deprecation\n return (navigator as any).platform || 'Unknown';\n}\n\nexport function detectBrowser(): BrowserInfo {\n const ua = navigator.userAgent;\n const platform = getPlatform();\n\n let name = 'Unknown';\n let version = '0';\n let majorVersion = 0;\n let isSmartTV = false;\n let isLegacyTV = false;\n let supportsIMA = true;\n let supportsModernJS = true;\n let recommendedAdPlayer: 'ima' | 'hls' = 'ima';\n let webOSVersion: number | undefined;\n let tizenVersion: number | undefined;\n let chromeVersionNum: number | undefined;\n\n const chromeVersion = getChromeVersion(ua);\n const webkitVersion = getWebKitVersion(ua);\n chromeVersionNum = chromeVersion > 0 ? chromeVersion : undefined;\n\n if (/Web0S|webOS|LG Browser|LGSTB/i.test(ua)) {\n name = 'LG WebOS';\n isSmartTV = true;\n \n let match = ua.match(/Web0S[/\\s]*([\\d.]+)/i) || ua.match(/webOS[/\\s]*([\\d.]+)/i);\n \n if (!match || !match[1]) {\n match = ua.match(/webOSTV[/\\s-]*([\\d.]+)/i) || ua.match(/webOS\\.TV[/\\s-]*([\\d.]+)/i);\n }\n \n if (match && match[1]) {\n version = match[1];\n const parts = version.split('.');\n majorVersion = parts[0] ? parseInt(parts[0], 10) : 0;\n webOSVersion = majorVersion;\n } else if (chromeVersion > 0) {\n if (chromeVersion >= 79) {\n webOSVersion = 6;\n version = '6.0';\n majorVersion = 6;\n } else if (chromeVersion >= 68) {\n webOSVersion = 5;\n version = '5.0';\n majorVersion = 5;\n } else if (chromeVersion >= 53) {\n webOSVersion = 4;\n version = '4.0';\n majorVersion = 4;\n } else if (chromeVersion >= 38) {\n webOSVersion = 3;\n version = '3.0';\n majorVersion = 3;\n } else {\n webOSVersion = 2;\n version = '2.0';\n majorVersion = 2;\n }\n } else {\n version = 'Unknown';\n webOSVersion = undefined;\n }\n\n if (webOSVersion !== undefined && webOSVersion >= 4) {\n supportsIMA = true;\n recommendedAdPlayer = 'ima';\n isLegacyTV = false;\n } else if (webOSVersion !== undefined && webOSVersion >= 3) {\n if (chromeVersion >= 53) {\n supportsIMA = true;\n recommendedAdPlayer = 'ima';\n isLegacyTV = false;\n } else {\n supportsIMA = false;\n recommendedAdPlayer = 'hls';\n isLegacyTV = true;\n }\n } else if (chromeVersion >= 53) {\n supportsIMA = true;\n recommendedAdPlayer = 'ima';\n isLegacyTV = false;\n } else {\n supportsIMA = false;\n recommendedAdPlayer = 'hls';\n isLegacyTV = true;\n }\n } else if (/Tizen/i.test(ua)) {\n name = 'Samsung Tizen';\n isSmartTV = true;\n const match = ua.match(/Tizen[/\\s]*([\\d.]+)/i);\n version = match && match[1] ? match[1] : 'Unknown';\n if (version !== 'Unknown') {\n const parts = version.split('.');\n majorVersion = parts[0] ? parseInt(parts[0], 10) : 0;\n tizenVersion = majorVersion;\n }\n \n if (tizenVersion !== undefined && tizenVersion >= 4) {\n supportsIMA = true;\n recommendedAdPlayer = 'ima';\n isLegacyTV = false;\n } else if (tizenVersion !== undefined && tizenVersion >= 3 && chromeVersion >= 47) {\n supportsIMA = true;\n recommendedAdPlayer = 'ima';\n isLegacyTV = false;\n } else if (chromeVersion >= 53) {\n supportsIMA = true;\n recommendedAdPlayer = 'ima';\n isLegacyTV = false;\n } else {\n supportsIMA = false;\n recommendedAdPlayer = 'hls';\n isLegacyTV = true;\n }\n } else if (/SMART-TV|SmartTV/i.test(ua)) {\n name = 'Smart TV';\n isSmartTV = true;\n if (chromeVersion >= 53) {\n supportsIMA = true;\n recommendedAdPlayer = 'ima';\n } else {\n supportsIMA = false;\n recommendedAdPlayer = 'hls';\n isLegacyTV = true;\n }\n } else if (/NetCast/i.test(ua)) {\n name = 'LG NetCast';\n isSmartTV = true;\n isLegacyTV = true;\n supportsIMA = false;\n recommendedAdPlayer = 'hls';\n } else if (/BRAVIA/i.test(ua)) {\n name = 'Sony BRAVIA';\n isSmartTV = true;\n if (chromeVersion >= 53) {\n supportsIMA = true;\n recommendedAdPlayer = 'ima';\n } else {\n supportsIMA = false;\n recommendedAdPlayer = 'hls';\n isLegacyTV = true;\n }\n } else {\n if (chromeVersion > 0) {\n name = 'Chrome';\n version = chromeVersion.toString();\n majorVersion = chromeVersion;\n\n if (chromeVersion < 50) {\n supportsIMA = false;\n supportsModernJS = false;\n recommendedAdPlayer = 'hls';\n }\n }\n\n if (webkitVersion > 0 && webkitVersion < 600) {\n supportsModernJS = false;\n if (chromeVersion < 50) {\n supportsIMA = false;\n recommendedAdPlayer = 'hls';\n }\n }\n }\n\n if (typeof Promise === 'undefined' ||\n typeof Map === 'undefined' ||\n typeof Set === 'undefined') {\n supportsModernJS = false;\n supportsIMA = false;\n recommendedAdPlayer = 'hls';\n }\n\n if (typeof URLSearchParams === 'undefined') {\n supportsModernJS = false;\n }\n\n return {\n name,\n version,\n majorVersion,\n isSmartTV,\n isLegacyTV,\n platform,\n supportsIMA,\n supportsModernJS,\n recommendedAdPlayer,\n webOSVersion,\n tizenVersion,\n chromeVersion: chromeVersionNum,\n };\n}\n\nexport function supportsGoogleIMA(): boolean {\n const browser = detectBrowser();\n\n if (browser.isLegacyTV) {\n return false;\n }\n\n if (typeof document === 'undefined' ||\n typeof document.createElement !== 'function') {\n return false;\n }\n\n try {\n const video = document.createElement('video');\n if (!video) {\n return false;\n }\n } catch (e) {\n return false;\n }\n\n if (typeof Promise === 'undefined') {\n return false;\n }\n\n return browser.supportsIMA;\n}\n\nexport function getRecommendedAdPlayer(): 'ima' | 'hls' {\n const browser = detectBrowser();\n return browser.recommendedAdPlayer;\n}\n\nexport function supportsModernJS(): boolean {\n try {\n return (\n typeof Promise !== 'undefined' &&\n typeof Map !== 'undefined' &&\n typeof Set !== 'undefined' &&\n typeof Array.from !== 'undefined' &&\n typeof Object.assign !== 'undefined' &&\n typeof Array.prototype.forEach !== 'undefined' &&\n typeof String.prototype.includes !== 'undefined'\n );\n } catch (e) {\n return false;\n }\n}\n\nexport function logBrowserInfo(debug: boolean = false): void {\n if (!debug) return;\n\n const browser = detectBrowser();\n const imaSupport = supportsGoogleIMA();\n\n console.log('[StormcloudVideoPlayer] Browser Compatibility Info:', {\n browser: `${browser.name} ${browser.version}`,\n platform: browser.platform,\n isSmartTV: browser.isSmartTV,\n isLegacyTV: browser.isLegacyTV,\n supportsIMA: imaSupport,\n supportsModernJS: browser.supportsModernJS,\n recommendedAdPlayer: browser.recommendedAdPlayer,\n ...(browser.webOSVersion !== undefined ? { webOSVersion: browser.webOSVersion } : {}),\n ...(browser.tizenVersion !== undefined ? { tizenVersion: browser.tizenVersion } : {}),\n ...(browser.chromeVersion !== undefined ? { chromeVersion: browser.chromeVersion } : {}),\n userAgent: navigator.userAgent,\n });\n}\n\nexport function getBrowserConfigOverrides(): {\n allowNativeHls?: boolean;\n} {\n const browser = detectBrowser();\n const overrides: { allowNativeHls?: boolean } = {};\n\n if (browser.isSmartTV) {\n overrides.allowNativeHls = true;\n }\n\n return overrides;\n}\n\nexport function supportsFeature(feature: string): boolean {\n switch (feature) {\n case 'ima':\n return supportsGoogleIMA();\n case 'urlsearchparams':\n return typeof URLSearchParams !== 'undefined';\n case 'textencoder':\n return typeof TextEncoder !== 'undefined';\n case 'promises':\n return typeof Promise !== 'undefined';\n case 'fetch':\n return typeof fetch !== 'undefined';\n case 'crypto':\n return typeof crypto !== 'undefined' && typeof crypto.subtle !== 'undefined';\n default:\n return false;\n }\n}\n\n","import React, {\n useEffect,\n useLayoutEffect,\n useRef,\n useState,\n useCallback,\n useMemo,\n useId,\n} from \"react\";\nimport {\n type SwirlOverlay,\n isOverlayActive,\n resolveImageUrl,\n} from \"../utils/overlays\";\n\ninterface VideoDimensions {\n nativeWidth: number;\n nativeHeight: number;\n displayWidth: number;\n displayHeight: number;\n offsetX: number;\n offsetY: number;\n scaleX: number;\n scaleY: number;\n}\n\ninterface OverlayRendererProps {\n overlays: SwirlOverlay[];\n currentTime: number;\n videoRef: React.RefObject<HTMLVideoElement | null>;\n coordinateSpace?: { width: number; height: number } | null;\n showcaseMode?: boolean;\n showcaseCycleMs?: number;\n}\n\nfunction computeVideoDimensions(\n video: HTMLVideoElement\n): VideoDimensions | null {\n const nativeWidth = video.videoWidth;\n const nativeHeight = video.videoHeight;\n if (!nativeWidth || !nativeHeight) return null;\n\n const displayWidth = video.offsetWidth;\n const displayHeight = video.offsetHeight;\n if (!displayWidth || !displayHeight) return null;\n\n const videoAspect = nativeWidth / nativeHeight;\n const displayAspect = displayWidth / displayHeight;\n\n let renderWidth: number;\n let renderHeight: number;\n let offsetX: number;\n let offsetY: number;\n\n if (videoAspect > displayAspect) {\n renderWidth = displayWidth;\n renderHeight = displayWidth / videoAspect;\n offsetX = 0;\n offsetY = (displayHeight - renderHeight) / 2;\n } else {\n renderHeight = displayHeight;\n renderWidth = displayHeight * videoAspect;\n offsetX = (displayWidth - renderWidth) / 2;\n offsetY = 0;\n }\n\n return {\n nativeWidth,\n nativeHeight,\n displayWidth: renderWidth,\n displayHeight: renderHeight,\n offsetX,\n offsetY,\n scaleX: renderWidth / nativeWidth,\n scaleY: renderHeight / nativeHeight,\n };\n}\n\nfunction ImageOverlay({ overlay }: { overlay: SwirlOverlay }) {\n const src = resolveImageUrl(overlay.image_url || \"\");\n if (!src) return null;\n return (\n <img\n src={src}\n alt={overlay.name}\n draggable={false}\n style={{\n width: \"100%\",\n height: \"100%\",\n objectFit: \"contain\",\n display: \"block\",\n pointerEvents: \"none\",\n userSelect: \"none\",\n }}\n />\n );\n}\n\nfunction TextOverlay({ overlay }: { overlay: SwirlOverlay }) {\n const text = overlay.content || \"\";\n return (\n <div\n style={{\n width: \"100%\",\n height: \"100%\",\n display: \"flex\",\n alignItems: \"center\",\n justifyContent: \"center\",\n color: \"#ffffff\",\n fontSize: \"clamp(10px, 1.4vw, 20px)\",\n fontFamily: \"Roboto, 'Segoe UI', Arial, sans-serif\",\n fontWeight: 600,\n textAlign: \"center\",\n padding: \"4px 8px\",\n boxSizing: \"border-box\",\n wordBreak: \"break-word\",\n textShadow: \"0 1px 4px rgba(0,0,0,0.7)\",\n pointerEvents: \"none\",\n userSelect: \"none\",\n lineHeight: 1.3,\n }}\n >\n {text}\n </div>\n );\n}\n\ninterface RSSItem {\n title: string;\n description: string;\n pubDate: string;\n author: string;\n category: string;\n}\n\nfunction parseRSSXml(xmlText: string, maxItems: number): RSSItem[] {\n const stripped = xmlText.replace(/^<\\?xml[^?]*\\?>\\s*/, \"\");\n const parser = new DOMParser();\n const doc = parser.parseFromString(stripped, \"text/xml\");\n const items = Array.from(doc.querySelectorAll(\"item\"))\n .map((item) => ({\n title: (item.querySelector(\"title\")?.textContent || \"\").replace(/<[^>]*>/g, \"\").trim(),\n description: (item.querySelector(\"description\")?.textContent || \"\").replace(/<[^>]*>/g, \"\").trim(),\n pubDate: item.querySelector(\"pubDate\")?.textContent || \"\",\n author: item.querySelector(\"author, dc\\\\:creator\")?.textContent || \"\",\n category: item.querySelector(\"category\")?.textContent || \"\",\n }))\n .filter((i) => i.title)\n .slice(0, maxItems);\n if (items.length === 0 && doc.querySelector(\"parsererror\")) {\n throw new Error(\"Invalid RSS XML\");\n }\n return items;\n}\n\nconst RSS_CACHE_TTL_MS = 60_000;\nconst rssCache = new Map<string, { promise: Promise<RSSItem[]>; expiresAt: number }>();\n\nfunction cachedFetchRSSItems(rssUrl: string, maxItems: number): Promise<RSSItem[]> {\n const now = Date.now();\n const cached = rssCache.get(rssUrl);\n if (cached && cached.expiresAt > now) return cached.promise;\n const promise = fetchRSSItems(rssUrl, maxItems).catch((err) => {\n rssCache.delete(rssUrl);\n throw err;\n });\n rssCache.set(rssUrl, { promise, expiresAt: now + RSS_CACHE_TTL_MS });\n return promise;\n}\n\nasync function fetchRSSItems(rssUrl: string, maxItems: number): Promise<RSSItem[]> {\n const encoded = encodeURIComponent(rssUrl);\n\n try {\n const origin = typeof window !== \"undefined\" ? window.location.origin : \"\";\n const resp = await fetch(`${origin}/api/rss-proxy?url=${encoded}`);\n if (resp.ok) {\n const text = await resp.text();\n if (text.includes(\"<item\")) return parseRSSXml(text, maxItems);\n }\n } catch { /* fall through */ }\n\n try {\n const resp = await fetch(`https://api.allorigins.win/get?url=${encoded}`);\n if (resp.ok) {\n const data = await resp.json();\n if (data.contents) return parseRSSXml(data.contents, maxItems);\n }\n } catch { /* fall through */ }\n\n try {\n const resp = await fetch(`https://corsproxy.io/?url=${encoded}`);\n if (resp.ok) {\n const text = await resp.text();\n if (text) return parseRSSXml(text, maxItems);\n }\n } catch { /* fall through */ }\n\n throw new Error(\"All RSS proxies failed\");\n}\n\nfunction ScrollerOverlay({ overlay }: { overlay: SwirlOverlay }) {\n const cfg = overlay.scroller_config;\n const uid = useId().replace(/:/g, \"\");\n\n const [rssItems, setRssItems] = useState<RSSItem[]>([]);\n const [rssLoading, setRssLoading] = useState(true);\n const [rssError, setRssError] = useState(false);\n\n const rssUrl = cfg?.rss_url || \"\";\n const maxItems = cfg?.max_items ?? 10;\n const autoRefresh = cfg?.auto_refresh !== false;\n const updateInterval = cfg?.update_interval ?? 5;\n\n useEffect(() => {\n if (!rssUrl || (cfg?.use_custom_text && cfg?.custom_text)) {\n setRssLoading(false);\n return;\n }\n let cancelled = false;\n setRssLoading(true);\n setRssError(false);\n cachedFetchRSSItems(rssUrl, maxItems)\n .then((items) => { if (!cancelled) { setRssItems(items); setRssError(false); } })\n .catch(() => { if (!cancelled) setRssError(true); })\n .finally(() => { if (!cancelled) setRssLoading(false); });\n return () => { cancelled = true; };\n }, [rssUrl, maxItems, cfg?.use_custom_text, cfg?.custom_text]);\n\n useEffect(() => {\n if (!rssUrl || !autoRefresh || (cfg?.use_custom_text && cfg?.custom_text)) return;\n const interval = setInterval(() => {\n rssCache.delete(rssUrl);\n cachedFetchRSSItems(rssUrl, maxItems)\n .then((items) => { setRssItems(items); setRssError(false); })\n .catch(() => { /* keep showing last good items */ });\n }, updateInterval * 60 * 1000);\n return () => clearInterval(interval);\n }, [rssUrl, autoRefresh, updateInterval, maxItems, cfg?.use_custom_text, cfg?.custom_text]);\n\n const sep = cfg?.separator_char ?? \"◆\";\n\n let segments: string[];\n if (cfg?.use_custom_text && cfg?.custom_text) {\n segments = [cfg.custom_text];\n } else if (rssItems.length > 0) {\n segments = rssItems.map((item) => {\n const parts: string[] = [];\n if (cfg?.show_title !== false && item.title) parts.push(item.title);\n if (cfg?.show_description && item.description) parts.push(item.description);\n if (cfg?.show_timestamp && item.pubDate) {\n try { parts.push(new Date(item.pubDate).toLocaleDateString()); } catch { /* ignore */ }\n }\n if (cfg?.show_author && item.author) parts.push(`— ${item.author}`);\n if (cfg?.show_category && item.category) parts.push(`[${item.category}]`);\n return parts.join(\" \");\n });\n } else if (rssLoading) {\n segments = [\"Loading feed…\"];\n } else if (rssError) {\n segments = overlay.content ? [overlay.content] : [\"RSS feed unavailable\"];\n } else if (overlay.content) {\n segments = [overlay.content];\n } else {\n segments = rssUrl ? [\"Loading feed…\"] : [\"RSS Ticker\"];\n }\n\n const scrollSpeed = cfg?.scroll_speed ?? 40;\n const direction = cfg?.direction ?? \"left\";\n const fontSize = cfg?.font_size ?? 15;\n const fontFamily = cfg?.font_family || \"Roboto, 'Segoe UI', Arial, sans-serif\";\n const fontWeight = cfg?.font_weight || \"700\";\n const textColor = cfg?.text_color || \"#ffffff\";\n const bgColor = cfg?.background_color || \"#0d0d1a\";\n const bgOpacity = cfg?.background_opacity !== undefined ? cfg.background_opacity / 100 : 0.95;\n const borderRadius = cfg?.border_radius ?? 0;\n const itemSpacing = cfg?.item_spacing ?? 60;\n const pad = cfg?.padding !== undefined && cfg.padding >= 0 ? cfg.padding : 8;\n\n const label = cfg?.label ?? \"NEWS\";\n const labelLine2 = cfg?.label_line2 ?? \"\";\n const labelColor = cfg?.label_color ?? \"#f97316\";\n const labelTextColor = cfg?.label_text_color ?? \"#ffffff\";\n const accentColor = cfg?.accent_color ?? labelColor;\n const showAccentLine = cfg?.show_accent_line !== false;\n const isEquitiesStrip = cfg?.preset === \"equities_strip\";\n\n const isHorizontal = direction === \"left\" || direction === \"right\";\n const isReverse = direction === \"right\" || direction === \"down\";\n\n const fullText = segments.join(` ${sep} `);\n const durationSec = Math.max(6, (fullText.length * 9) / scrollSpeed);\n\n const animId = `sc-ticker-${overlay.id}-${uid}`;\n const keyframes = isHorizontal\n ? `@keyframes ${animId} {\n ${isReverse\n ? \"0% { transform: translateX(-50%); } 100% { transform: translateX(0%); }\"\n : \"0% { transform: translateX(0); } 100% { transform: translateX(-50%); }\"}\n }`\n : `@keyframes ${animId} {\n ${isReverse\n ? \"0% { transform: translateY(-50%); } 100% { transform: translateY(0%); }\"\n : \"0% { transform: translateY(0); } 100% { transform: translateY(-50%); }\"}\n }`;\n\n return (\n <>\n <style>{keyframes}</style>\n <div\n style={{\n width: \"100%\",\n height: \"100%\",\n display: \"flex\",\n flexDirection: \"column\",\n overflow: \"hidden\",\n borderRadius: borderRadius > 0 ? `${borderRadius}px` : undefined,\n backgroundColor: `rgba(${hexToRgb(bgColor)}, ${bgOpacity})`,\n fontFamily,\n fontSize: `${fontSize}px`,\n fontWeight,\n color: textColor,\n pointerEvents: \"none\",\n userSelect: \"none\",\n }}\n >\n {showAccentLine && (\n <div\n style={{\n height: isEquitiesStrip ? 2 : 3,\n background: accentColor,\n flexShrink: 0,\n width: \"100%\",\n }}\n />\n )}\n\n <div\n style={{\n display: \"flex\",\n flex: 1,\n overflow: \"hidden\",\n minHeight: 0,\n alignItems: \"center\",\n padding: isEquitiesStrip\n ? `${Math.max(2, pad * 0.5)}px ${pad}px`\n : `${Math.max(4, pad * 0.75)}px ${pad}px`,\n gap: isEquitiesStrip ? Math.max(4, Math.round(pad * 0.75)) : Math.max(6, pad),\n boxSizing: \"border-box\",\n }}\n >\n {label && (\n <div\n style={{\n background: labelColor,\n color: labelTextColor,\n padding: isEquitiesStrip ? \"6px 12px\" : \"10px 14px\",\n display: \"flex\",\n flexDirection: isEquitiesStrip ? \"row\" : \"column\",\n alignItems: \"center\",\n justifyContent: \"center\",\n flexShrink: 0,\n textAlign: \"center\",\n gap: isEquitiesStrip ? 0 : 2,\n borderRadius: Math.max(2, borderRadius > 0 ? borderRadius : 6),\n boxShadow: isEquitiesStrip\n ? \"inset 0 1px 0 rgba(255,255,255,0.08)\"\n : \"0 2px 8px rgba(0,0,0,0.35)\",\n alignSelf: \"stretch\",\n maxWidth: isEquitiesStrip ? \"min(200px, 28%)\" : undefined,\n }}\n >\n <span\n style={{\n fontWeight: isEquitiesStrip ? 700 : 800,\n fontSize: isEquitiesStrip ? \"0.82em\" : \"0.78em\",\n letterSpacing: isEquitiesStrip ? \"0.04em\" : \"0.08em\",\n lineHeight: 1.2,\n textTransform: isEquitiesStrip ? \"none\" : \"uppercase\",\n whiteSpace: isEquitiesStrip ? \"normal\" : \"nowrap\",\n textAlign: isEquitiesStrip ? \"left\" : \"center\",\n }}\n >\n {label}\n </span>\n {labelLine2 && !isEquitiesStrip && (\n <span\n style={{\n fontWeight: 600,\n fontSize: \"0.58em\",\n letterSpacing: \"0.06em\",\n lineHeight: 1.15,\n opacity: 0.92,\n whiteSpace: \"nowrap\",\n }}\n >\n {labelLine2}\n </span>\n )}\n </div>\n )}\n\n {label && (\n <div\n style={{\n width: isEquitiesStrip ? 1 : 2,\n alignSelf: \"stretch\",\n minHeight: isEquitiesStrip ? 20 : 24,\n background: accentColor,\n flexShrink: 0,\n borderRadius: 1,\n opacity: 0.85,\n }}\n />\n )}\n\n <div\n style={{\n flex: 1,\n overflow: \"hidden\",\n position: \"relative\",\n display: \"flex\",\n alignItems: \"center\",\n minWidth: 0,\n }}\n >\n {isHorizontal ? (\n <div\n style={{\n display: \"inline-flex\",\n whiteSpace: \"nowrap\",\n animation: `${animId} ${durationSec}s linear infinite`,\n willChange: \"transform\",\n }}\n >\n {[0, 1].map((copy) => (\n <span key={copy} style={{ paddingRight: `${itemSpacing}px` }}>\n {segments.map((seg, i) => (\n <React.Fragment key={i}>\n {i > 0 && (\n <span style={{ opacity: 0.5, margin: \"0 8px\" }}>{sep}</span>\n )}\n <span style={{ textShadow: \"0 1px 3px rgba(0,0,0,0.6)\" }}>{seg}</span>\n </React.Fragment>\n ))}\n </span>\n ))}\n </div>\n ) : (\n <div\n style={{\n display: \"flex\",\n flexDirection: \"column\",\n whiteSpace: \"nowrap\",\n animation: `${animId} ${durationSec}s linear infinite`,\n willChange: \"transform\",\n }}\n >\n {[0, 1].map((copy) =>\n segments.map((seg, i) => (\n <div key={`${copy}-${i}`} style={{ paddingBottom: `${itemSpacing / 4}px` }}>\n {seg}\n </div>\n ))\n )}\n </div>\n )}\n </div>\n </div>\n </div>\n </>\n );\n}\n\nfunction parseConfig<T>(content?: string): T | null {\n if (!content) return null;\n try { return JSON.parse(content) as T; } catch { return null; }\n}\n\ninterface OverlaySize { w: number; h: number; }\n\ninterface ScoreBugCfg { homeTeam: string; awayTeam: string; homeScore: number; awayScore: number; period: string; clock: string; sponsorText: string; sponsorImageUrl: string; backgroundColor: string; textColor: string; accentColor: string; }\ninterface LowerThirdCfg { headline: string; subtitle: string; sponsorText: string; sponsorImageUrl: string; backgroundColor: string; textColor: string; accentColor: string; style: string; }\ninterface QrCodeCfg { url: string; ctaText: string; description: string; size: number; backgroundColor: string; textColor: string; accentColor: string; }\ninterface ComingUpNextCfg { title: string; subtitle: string; scheduledTime: string; thumbnailUrl: string; backgroundColor: string; textColor: string; accentColor: string; }\ninterface ContextualTriggerCfg { triggerType: string; headline: string; message: string; iconType: string; backgroundColor: string; textColor: string; accentColor: string; animationStyle: string; }\ninterface OddsBettingCfg { eventTitle: string; options: Array<{ label: string; odds: string }>; sponsorText: string; backgroundColor: string; textColor: string; accentColor: string; oddsFormat: string; }\ninterface BreakingNewsCfg { headline: string; body: string; urgency: string; backgroundColor: string; textColor: string; accentColor: string; }\ninterface CountdownCfg { eventName: string; targetTime: string; message: string; showDays: boolean; showHours: boolean; showMinutes: boolean; showSeconds: boolean; backgroundColor: string; textColor: string; accentColor: string; }\n\nfunction parseClockMMSS(clock: string | undefined): number | null {\n if (!clock) return null;\n const m = /^\\s*(\\d{1,3}):([0-5]?\\d)\\s*$/.exec(clock);\n if (!m) return null;\n return parseInt(m[1]!, 10) * 60 + parseInt(m[2]!, 10);\n}\n\nfunction formatClockMMSS(totalSec: number): string {\n const s = Math.max(0, Math.floor(totalSec));\n const mm = Math.floor(s / 60);\n const ss = s % 60;\n return `${mm}:${ss.toString().padStart(2, \"0\")}`;\n}\n\nfunction useScoreBugClock(overlayId: number, sourceClock: string | undefined): string | null {\n const initialSec = parseClockMMSS(sourceClock);\n const [now, setNow] = useState<number>(() => Date.now());\n const startRef = useRef<{ id: number; source: string; at: number; seconds: number } | null>(null);\n\n useEffect(() => {\n if (initialSec === null) {\n startRef.current = null;\n return;\n }\n startRef.current = {\n id: overlayId,\n source: sourceClock || \"\",\n at: Date.now(),\n seconds: initialSec,\n };\n setNow(Date.now());\n const tick = window.setInterval(() => setNow(Date.now()), 500);\n return () => clearInterval(tick);\n }, [overlayId, sourceClock, initialSec]);\n\n if (initialSec === null || !startRef.current) return null;\n const elapsed = Math.floor((now - startRef.current.at) / 1000);\n const remaining = Math.max(0, startRef.current.seconds - elapsed);\n return formatClockMMSS(remaining);\n}\n\nfunction ScoreBugOverlay({ overlay, size }: { overlay: SwirlOverlay; size: OverlaySize }) {\n const cfg = parseConfig<ScoreBugCfg>(overlay.content);\n const liveClock = useScoreBugClock(overlay.id, cfg?.clock);\n if (!cfg) return null;\n const f = Math.max(6, size.w * 0.052);\n const displayClock = liveClock ?? cfg.clock ?? \"\";\n const displayPeriod = cfg.period ?? \"\";\n const showMiddleCol = Boolean(displayPeriod || displayClock);\n return (\n <div\n style={{\n width: \"100%\",\n height: \"100%\",\n borderRadius: Math.max(2, size.w * 0.028),\n display: \"flex\",\n flexDirection: \"column\",\n background: cfg.backgroundColor,\n color: cfg.textColor,\n fontFamily: \"'Inter', 'Roboto', 'Segoe UI', system-ui, sans-serif\",\n overflow: \"hidden\",\n pointerEvents: \"none\",\n userSelect: \"none\",\n fontSize: `${f}px`,\n boxShadow: \"0 8px 28px rgba(0,0,0,0.45)\",\n }}\n >\n <div\n style={{\n flex: 1,\n display: \"flex\",\n alignItems: \"center\",\n padding: `${f * 0.42}px ${f * 0.85}px`,\n gap: f * 0.45,\n minHeight: 0,\n }}\n >\n <div style={{ flex: 1, textAlign: \"center\", minWidth: 0, padding: `0 ${f * 0.15}px` }}>\n <div\n style={{\n fontSize: \"1.05em\",\n fontWeight: 800,\n letterSpacing: \"0.02em\",\n overflow: \"hidden\",\n textOverflow: \"ellipsis\",\n whiteSpace: \"nowrap\",\n }}\n >\n {cfg.homeTeam}\n </div>\n <div style={{ fontSize: \"1.75em\", fontWeight: 900, lineHeight: 1.05, marginTop: f * 0.08 }}>\n {cfg.homeScore}\n </div>\n </div>\n {showMiddleCol && (\n <div\n style={{\n fontSize: \"0.88em\",\n textAlign: \"center\",\n fontWeight: 600,\n opacity: 0.92,\n color: cfg.textColor,\n padding: `0 ${f * 0.5}px`,\n flexShrink: 0,\n lineHeight: 1.25,\n textTransform: \"uppercase\",\n letterSpacing: \"0.04em\",\n }}\n >\n {displayPeriod && <div>{displayPeriod}</div>}\n {displayClock && (\n <div style={{ fontWeight: 700, opacity: 1 }}>{displayClock}</div>\n )}\n </div>\n )}\n <div style={{ flex: 1, textAlign: \"center\", minWidth: 0, padding: `0 ${f * 0.15}px` }}>\n <div\n style={{\n fontSize: \"1.05em\",\n fontWeight: 800,\n letterSpacing: \"0.02em\",\n overflow: \"hidden\",\n textOverflow: \"ellipsis\",\n whiteSpace: \"nowrap\",\n }}\n >\n {cfg.awayTeam}\n </div>\n <div style={{ fontSize: \"1.75em\", fontWeight: 900, lineHeight: 1.05, marginTop: f * 0.08 }}>\n {cfg.awayScore}\n </div>\n </div>\n </div>\n {(cfg.sponsorText || cfg.sponsorImageUrl) && (\n <div\n style={{\n fontSize: \"0.72em\",\n textAlign: \"center\",\n fontWeight: 600,\n opacity: 0.88,\n padding: `${f * 0.34}px ${f * 0.55}px`,\n borderTop: `1px solid ${cfg.accentColor}55`,\n display: \"flex\",\n alignItems: \"center\",\n justifyContent: \"center\",\n gap: f * 0.45,\n overflow: \"hidden\",\n letterSpacing: \"0.04em\",\n textTransform: \"uppercase\",\n background: `linear-gradient(180deg, rgba(0,0,0,0.12) 0%, rgba(0,0,0,0.22) 100%)`,\n }}\n >\n {cfg.sponsorImageUrl && (\n <img src={cfg.sponsorImageUrl} alt=\"sponsor\" style={{ height: `${f * 1.35}px`, objectFit: \"contain\", flexShrink: 0 }} />\n )}\n {cfg.sponsorText && (\n <span style={{ overflow: \"hidden\", textOverflow: \"ellipsis\", whiteSpace: \"nowrap\" }}>{cfg.sponsorText}</span>\n )}\n </div>\n )}\n </div>\n );\n}\n\nfunction LowerThirdOverlay({ overlay, size }: { overlay: SwirlOverlay; size: OverlaySize }) {\n const cfg = parseConfig<LowerThirdCfg>(overlay.content);\n if (!cfg) return null;\n const f = Math.max(6, size.w * 0.05);\n const accentH = Math.max(3, size.h * 0.038);\n return (\n <div\n style={{\n width: \"100%\",\n height: \"100%\",\n borderRadius: Math.max(2, size.w * 0.018),\n display: \"flex\",\n flexDirection: \"column\",\n justifyContent: \"flex-end\",\n background: cfg.backgroundColor,\n color: cfg.textColor,\n fontFamily: \"'Inter', 'Roboto', 'Segoe UI', system-ui, sans-serif\",\n overflow: \"hidden\",\n pointerEvents: \"none\",\n userSelect: \"none\",\n fontSize: `${f}px`,\n boxShadow: \"0 10px 32px rgba(0,0,0,0.4)\",\n }}\n >\n <div style={{ width: \"100%\", height: accentH, backgroundColor: cfg.accentColor, flexShrink: 0 }} />\n <div\n style={{\n flex: 1,\n display: \"flex\",\n flexDirection: \"column\",\n justifyContent: \"center\",\n padding: `${f * 0.62}px ${f * 1.05}px`,\n minHeight: 0,\n gap: f * 0.18,\n }}\n >\n <div\n style={{\n fontSize: \"1.28em\",\n fontWeight: 800,\n lineHeight: 1.22,\n letterSpacing: \"0.01em\",\n textShadow: \"0 2px 6px rgba(0,0,0,0.55)\",\n }}\n >\n {cfg.headline}\n </div>\n <div\n style={{\n fontSize: \"0.94em\",\n fontWeight: 500,\n opacity: 0.92,\n lineHeight: 1.35,\n color: cfg.textColor,\n }}\n >\n {cfg.subtitle}\n </div>\n </div>\n {(cfg.sponsorText || cfg.sponsorImageUrl) && (\n <div\n style={{\n fontSize: \"0.68em\",\n fontWeight: 600,\n opacity: 0.72,\n padding: `${f * 0.28}px ${f * 1.05}px ${f * 0.48}px`,\n display: \"flex\",\n alignItems: \"center\",\n gap: f * 0.4,\n overflow: \"hidden\",\n letterSpacing: \"0.06em\",\n textTransform: \"uppercase\",\n borderTop: `1px solid rgba(255,255,255,0.08)`,\n }}\n >\n {cfg.sponsorImageUrl && (\n <img src={cfg.sponsorImageUrl} alt=\"sponsor\" style={{ height: `${f * 1.25}px`, objectFit: \"contain\", flexShrink: 0 }} />\n )}\n {cfg.sponsorText && (\n <span style={{ overflow: \"hidden\", textOverflow: \"ellipsis\", whiteSpace: \"nowrap\" }}>{cfg.sponsorText}</span>\n )}\n </div>\n )}\n </div>\n );\n}\n\nfunction QrCodeOverlay({ overlay, size }: { overlay: SwirlOverlay; size: OverlaySize }) {\n const cfg = parseConfig<QrCodeCfg>(overlay.content);\n if (!cfg) return null;\n const qrSide = Math.max(32, Math.min(size.w, size.h) * 0.55);\n const qrUrl = `https://api.qrserver.com/v1/create-qr-code/?size=${Math.round(qrSide * 2)}x${Math.round(qrSide * 2)}&data=${encodeURIComponent(cfg.url || \"https://example.com\")}`;\n const f = Math.max(6, size.w * 0.06);\n return (\n <div style={{ width: \"100%\", height: \"100%\", borderRadius: Math.max(2, size.w * 0.035), display: \"flex\", flexDirection: \"column\", alignItems: \"center\", justifyContent: \"center\", gap: f * 0.4, background: cfg.backgroundColor, color: cfg.textColor, fontFamily: \"Roboto, 'Segoe UI', Arial, sans-serif\", padding: f * 0.6, boxSizing: \"border-box\", pointerEvents: \"none\", userSelect: \"none\", overflow: \"hidden\" }}>\n <div style={{ flexShrink: 0, background: \"#fff\", borderRadius: Math.max(2, qrSide * 0.06), padding: Math.max(2, qrSide * 0.06), lineHeight: 0 }}>\n <img src={qrUrl} alt=\"QR Code\" style={{ width: `${qrSide}px`, height: `${qrSide}px`, display: \"block\" }} />\n </div>\n <div style={{ fontSize: `${f * 1.1}px`, fontWeight: 700, textAlign: \"center\", color: cfg.accentColor, overflow: \"hidden\", textOverflow: \"ellipsis\", whiteSpace: \"nowrap\", width: \"100%\" }}>{cfg.ctaText}</div>\n {cfg.description && <div style={{ fontSize: `${f * 0.75}px`, opacity: 0.6, textAlign: \"center\", overflow: \"hidden\", textOverflow: \"ellipsis\", whiteSpace: \"nowrap\", width: \"100%\" }}>{cfg.description}</div>}\n </div>\n );\n}\n\nfunction ComingUpNextOverlay({ overlay, size }: { overlay: SwirlOverlay; size: OverlaySize }) {\n const cfg = parseConfig<ComingUpNextCfg>(overlay.content);\n if (!cfg) return null;\n const f = Math.max(8, Math.min(size.h * 0.13, size.w * 0.048));\n const showSubtitle = size.h >= 60;\n const showThumbnail = false;\n const thumbW = 0;\n return (\n <div style={{\n width: \"100%\", height: \"100%\",\n borderRadius: Math.max(2, size.w * 0.025),\n display: \"flex\",\n background: cfg.backgroundColor,\n color: cfg.textColor,\n fontFamily: \"'Arial', 'Helvetica Neue', Helvetica, sans-serif\",\n overflow: \"hidden\",\n pointerEvents: \"none\", userSelect: \"none\",\n fontSize: `${f}px`,\n WebkitFontSmoothing: \"antialiased\",\n } as React.CSSProperties}>\n <div style={{ width: Math.max(3, size.w * 0.018), flexShrink: 0, backgroundColor: cfg.accentColor }} />\n <div style={{\n flex: 1, display: \"flex\", flexDirection: \"column\", justifyContent: \"center\",\n padding: `${f * 0.35}px ${f * 0.75}px`,\n minWidth: 0, gap: `${f * 0.08}px`,\n }}>\n <div style={{\n fontSize: \"0.7em\", fontWeight: 700,\n textTransform: \"uppercase\", letterSpacing: \"0.09em\",\n color: cfg.accentColor, lineHeight: 1,\n }}>\n Coming Up Next\n </div>\n <div style={{\n fontSize: \"1.2em\", fontWeight: 700, lineHeight: 1.2,\n overflow: \"hidden\", textOverflow: \"ellipsis\", whiteSpace: \"nowrap\",\n }}>\n {cfg.title}\n </div>\n {showSubtitle && (\n <div style={{\n fontSize: \"0.82em\", opacity: 0.65, lineHeight: 1.1,\n overflow: \"hidden\", textOverflow: \"ellipsis\", whiteSpace: \"nowrap\",\n }}>\n {cfg.subtitle}\n </div>\n )}\n {cfg.scheduledTime && (\n <div style={{\n fontSize: \"0.9em\", fontWeight: 700,\n color: cfg.accentColor, lineHeight: 1,\n }}>\n {cfg.scheduledTime}\n </div>\n )}\n </div>\n {showThumbnail && (\n <div style={{ flexShrink: 0, width: `${thumbW}px`, overflow: \"hidden\" }}>\n <img\n src={cfg.thumbnailUrl}\n alt=\"\"\n style={{ width: \"100%\", height: \"100%\", objectFit: \"cover\", display: \"block\" }}\n />\n </div>\n )}\n </div>\n );\n}\n\nfunction ContextualTriggerOverlay({ overlay, size }: { overlay: SwirlOverlay; size: OverlaySize }) {\n const cfg = parseConfig<ContextualTriggerCfg>(overlay.content);\n if (!cfg) return null;\n const icons: Record<string, string> = { alert: \"\\u26A0\\uFE0F\", celebration: \"\\uD83C\\uDF89\", info: \"\\u2139\\uFE0F\", warning: \"\\uD83D\\uDD14\" };\n const f = Math.max(6, size.w * 0.05);\n return (\n <div style={{ width: \"100%\", height: \"100%\", borderRadius: Math.max(2, size.w * 0.035), display: \"flex\", alignItems: \"center\", gap: f * 0.8, padding: `0 ${f * 1.2}px`, background: cfg.backgroundColor, color: cfg.textColor, fontFamily: \"Roboto, 'Segoe UI', Arial, sans-serif\", borderLeft: `${Math.max(2, size.w * 0.02)}px solid ${cfg.accentColor}`, boxSizing: \"border-box\", pointerEvents: \"none\", userSelect: \"none\", fontSize: `${f}px` }}>\n <span style={{ fontSize: \"2em\", flexShrink: 0 }}>{icons[cfg.iconType] || \"\\u26A1\"}</span>\n <div style={{ flex: 1, minWidth: 0 }}>\n <div style={{ fontSize: \"1.3em\", fontWeight: 700, overflow: \"hidden\", textOverflow: \"ellipsis\", whiteSpace: \"nowrap\" }}>{cfg.headline}</div>\n <div style={{ fontSize: \"0.9em\", opacity: 0.7, overflow: \"hidden\", textOverflow: \"ellipsis\", whiteSpace: \"nowrap\" }}>{cfg.message}</div>\n </div>\n </div>\n );\n}\n\nfunction OddsBettingOverlay({ overlay, size }: { overlay: SwirlOverlay; size: OverlaySize }) {\n const cfg = parseConfig<OddsBettingCfg>(overlay.content);\n if (!cfg) return null;\n const f = Math.max(6, size.w * 0.052);\n return (\n <div style={{ width: \"100%\", height: \"100%\", borderRadius: Math.max(2, size.w * 0.035), display: \"flex\", flexDirection: \"column\", padding: f * 0.8, background: cfg.backgroundColor, color: cfg.textColor, fontFamily: \"Roboto, 'Segoe UI', Arial, sans-serif\", boxSizing: \"border-box\", pointerEvents: \"none\", userSelect: \"none\", fontSize: `${f}px` }}>\n <div style={{ fontSize: \"0.9em\", fontWeight: 700, textTransform: \"uppercase\", letterSpacing: \"0.05em\", color: cfg.accentColor, marginBottom: f * 0.4 }}>{cfg.eventTitle}</div>\n <div style={{ flex: 1, display: \"flex\", flexDirection: \"column\", gap: f * 0.2, justifyContent: \"center\" }}>\n {(cfg.options || []).slice(0, 5).map((opt, i) => (\n <div key={i} style={{ display: \"flex\", justifyContent: \"space-between\", alignItems: \"center\", padding: `${f * 0.2}px ${f * 0.6}px`, borderRadius: Math.max(2, f * 0.3), background: `${cfg.accentColor}15`, fontSize: \"1em\" }}>\n <span style={{ overflow: \"hidden\", textOverflow: \"ellipsis\", whiteSpace: \"nowrap\", flex: 1 }}>{opt.label}</span>\n <span style={{ fontWeight: 700, marginLeft: f * 0.8, flexShrink: 0, color: cfg.accentColor }}>{opt.odds}</span>\n </div>\n ))}\n </div>\n {cfg.sponsorText && <div style={{ fontSize: \"0.7em\", opacity: 0.4, textAlign: \"center\", marginTop: f * 0.4 }}>{cfg.sponsorText}</div>}\n </div>\n );\n}\n\nfunction BreakingNewsOverlay({ overlay, size }: { overlay: SwirlOverlay; size: OverlaySize }) {\n const cfg = parseConfig<BreakingNewsCfg>(overlay.content);\n if (!cfg) return null;\n const urgencyColors: Record<string, string> = { breaking: \"#dc2626\", urgent: \"#ea580c\", normal: \"#2563eb\" };\n const labelBg = urgencyColors[cfg.urgency] || urgencyColors.normal;\n const label = cfg.urgency === \"breaking\" ? \"BREAKING\" : cfg.urgency === \"urgent\" ? \"URGENT\" : \"NEWS\";\n const f = Math.max(6, size.w * 0.05);\n return (\n <div style={{ width: \"100%\", height: \"100%\", borderRadius: Math.max(2, size.w * 0.02), display: \"flex\", alignItems: \"center\", background: cfg.backgroundColor, color: cfg.textColor, fontFamily: \"Roboto, 'Segoe UI', Arial, sans-serif\", overflow: \"hidden\", pointerEvents: \"none\", userSelect: \"none\", fontSize: `${f}px` }}>\n <div style={{ padding: `0 ${f * 0.8}px`, height: \"100%\", display: \"flex\", alignItems: \"center\", background: labelBg, color: \"#fff\", fontSize: \"1em\", fontWeight: 900, textTransform: \"uppercase\", letterSpacing: \"0.05em\", flexShrink: 0 }}>{label}</div>\n <div style={{ flex: 1, padding: `0 ${f * 1.0}px`, minWidth: 0 }}>\n <div style={{ fontSize: \"1.3em\", fontWeight: 700, overflow: \"hidden\", textOverflow: \"ellipsis\", whiteSpace: \"nowrap\" }}>{cfg.headline}</div>\n {cfg.body && <div style={{ fontSize: \"0.9em\", opacity: 0.7, overflow: \"hidden\", textOverflow: \"ellipsis\", whiteSpace: \"nowrap\" }}>{cfg.body}</div>}\n </div>\n </div>\n );\n}\n\nfunction calcCountdownRemaining(targetTime: string) {\n const diff = Math.max(0, new Date(targetTime).getTime() - Date.now());\n return {\n d: Math.floor(diff / 86400000),\n h: Math.floor((diff % 86400000) / 3600000),\n m: Math.floor((diff % 3600000) / 60000),\n s: Math.floor((diff % 60000) / 1000),\n expired: diff === 0,\n };\n}\n\nfunction CountdownOverlay({ overlay, size }: { overlay: SwirlOverlay; size: OverlaySize }) {\n const cfg = parseConfig<CountdownCfg>(overlay.content);\n const targetTime = cfg?.targetTime ?? \"\";\n const [remaining, setRemaining] = useState(() =>\n targetTime ? calcCountdownRemaining(targetTime) : { d: 0, h: 0, m: 0, s: 0, expired: false }\n );\n\n useEffect(() => {\n if (!targetTime) return;\n setRemaining(calcCountdownRemaining(targetTime));\n const id = setInterval(() => setRemaining(calcCountdownRemaining(targetTime)), 1000);\n return () => clearInterval(id);\n }, [targetTime]);\n\n if (!cfg) return null;\n\n const f = Math.max(6, size.w * 0.055);\n const pad = (n: number) => String(n).padStart(2, \"0\");\n const units: Array<{ show: boolean; value: string; label: string }> = [\n { show: cfg.showDays, value: pad(remaining.d), label: \"DAYS\" },\n { show: cfg.showHours, value: pad(remaining.h), label: \"HRS\" },\n { show: cfg.showMinutes, value: pad(remaining.m), label: \"MIN\" },\n { show: cfg.showSeconds, value: pad(remaining.s), label: \"SEC\" },\n ];\n\n return (\n <div style={{ width: \"100%\", height: \"100%\", borderRadius: Math.max(2, size.w * 0.035), display: \"flex\", flexDirection: \"column\", alignItems: \"center\", justifyContent: \"center\", padding: f * 0.8, background: cfg.backgroundColor, color: cfg.textColor, fontFamily: \"Roboto, 'Segoe UI', Arial, sans-serif\", boxSizing: \"border-box\", pointerEvents: \"none\", userSelect: \"none\", fontSize: `${f}px` }}>\n <div style={{ fontSize: \"0.8em\", fontWeight: 600, textTransform: \"uppercase\", letterSpacing: \"0.05em\", color: cfg.accentColor, marginBottom: f * 0.4 }}>{cfg.eventName}</div>\n {remaining.expired ? (\n <div style={{ fontSize: \"1em\", fontWeight: 700, opacity: 0.6 }}>{cfg.message || \"Event ended\"}</div>\n ) : (\n <div style={{ display: \"flex\", gap: f * 0.6, alignItems: \"center\" }}>\n {units.filter(u => u.show).map((u, i, arr) => (\n <React.Fragment key={u.label}>\n <div style={{ textAlign: \"center\" }}>\n <div style={{ fontSize: \"2em\", fontWeight: 900, lineHeight: 1, borderRadius: Math.max(2, f * 0.4), padding: `${f * 0.2}px ${f * 0.4}px`, background: `${cfg.accentColor}20` }}>{u.value}</div>\n <div style={{ fontSize: \"0.5em\", opacity: 0.5, marginTop: f * 0.2 }}>{u.label}</div>\n </div>\n {i < arr.length - 1 && <div style={{ fontSize: \"1.8em\", fontWeight: 700, opacity: 0.3 }}>:</div>}\n </React.Fragment>\n ))}\n </div>\n )}\n {!remaining.expired && cfg.message && <div style={{ fontSize: \"0.8em\", opacity: 0.6, marginTop: f * 0.4, textAlign: \"center\" }}>{cfg.message}</div>}\n </div>\n );\n}\n\nfunction ShapeOverlay({ overlay, size }: { overlay: SwirlOverlay; size: OverlaySize }) {\n const f = Math.max(6, size.w * 0.05);\n return (\n <div style={{ width: \"100%\", height: \"100%\", borderRadius: Math.max(2, size.w * 0.03), background: \"rgba(99, 102, 241, 0.2)\", border: \"2px solid rgba(99, 102, 241, 0.4)\", display: \"flex\", alignItems: \"center\", justifyContent: \"center\", pointerEvents: \"none\", userSelect: \"none\" }}>\n <div style={{ fontSize: `${f}px`, fontWeight: 500, color: \"rgba(163, 163, 163, 0.8)\", textTransform: \"uppercase\" }}>{overlay.name}</div>\n </div>\n );\n}\n\nfunction hexToRgb(hex: string): string {\n if (!hex || !hex.startsWith(\"#\")) return \"0,0,0\";\n const clean = hex.slice(1);\n const num = parseInt(clean.length === 3 ? clean.replace(/./g, \"$&$&\") : clean, 16);\n return `${(num >> 16) & 255},${(num >> 8) & 255},${num & 255}`;\n}\n\ninterface OverlayFadeState {\n overlay: SwirlOverlay;\n visible: boolean;\n}\n\nconst FADE_DURATION_MS = 1000;\n\ntype EnterAnimation =\n | \"fade\"\n | \"slide_from_left\"\n | \"slide_from_right\"\n | \"slide_from_top\"\n | \"slide_from_bottom\";\n\nconst ENTER_ANIMATION_ALIASES: Record<string, EnterAnimation> = {\n fade: \"fade\",\n slide_from_left: \"slide_from_left\",\n slide_from_right: \"slide_from_right\",\n slide_from_top: \"slide_from_top\",\n slide_from_bottom: \"slide_from_bottom\",\n slide_left: \"slide_from_left\",\n slide_right: \"slide_from_right\",\n slide_up: \"slide_from_top\",\n slide_down: \"slide_from_bottom\",\n};\n\nfunction normalizeEnterAnimation(v: unknown): EnterAnimation | null {\n if (typeof v !== \"string\") return null;\n return ENTER_ANIMATION_ALIASES[v] ?? null;\n}\n\nfunction getEnterAnimation(overlay: SwirlOverlay): EnterAnimation {\n const flat = (overlay as unknown as { enter_animation?: unknown })\n .enter_animation;\n const fromFlat = normalizeEnterAnimation(flat);\n if (fromFlat) return fromFlat;\n if (overlay.content) {\n try {\n const parsed = JSON.parse(overlay.content) as Record<string, unknown>;\n const fromContent = normalizeEnterAnimation(parsed?.enterAnimation);\n if (fromContent) return fromContent;\n } catch {\n // ignore malformed content\n }\n }\n return \"fade\";\n}\n\nfunction enterHiddenTransform(anim: EnterAnimation): string {\n switch (anim) {\n case \"slide_from_left\":\n return \"translateX(-120%)\";\n case \"slide_from_right\":\n return \"translateX(120%)\";\n case \"slide_from_top\":\n return \"translateY(-120%)\";\n case \"slide_from_bottom\":\n return \"translateY(120%)\";\n default:\n return \"\";\n }\n}\n\nconst SHOWCASE_CYCLE_MS_DEFAULT = 36_000;\nconst SHOWCASE_MIN_BEAT_MS = 6_000;\nconst BEAT_POP_IN_MS = 520;\nconst BEAT_POP_OUT_MS = 520;\n\nconst SHOWCASE_PERSISTENT_TYPES: ReadonlySet<string> = new Set([\n \"scroller\",\n \"breaking_news\",\n \"image\",\n \"text\",\n \"shape\",\n \"countdown\",\n \"qr_code\",\n \"coming_up_next\",\n \"score_bug\",\n]);\n\nfunction easeOutCubic(t: number): number {\n const u = 1 - t;\n return 1 - u * u * u;\n}\n\nfunction easeInCubic(t: number): number {\n return t * t * t;\n}\n\nfunction easeOutBack(t: number): number {\n const c1 = 1.70158;\n const c3 = c1 + 1;\n return 1 + c3 * (t - 1) ** 3 + c1 * (t - 1) ** 2;\n}\n\nfunction beatOpacity(phase: number, beatMs: number): number {\n if (phase < BEAT_POP_IN_MS) return easeOutCubic(phase / BEAT_POP_IN_MS);\n const holdEnd = beatMs - BEAT_POP_OUT_MS;\n if (phase >= holdEnd) {\n return Math.max(\n 0,\n 1 - easeInCubic((phase - holdEnd) / BEAT_POP_OUT_MS)\n );\n }\n return 1;\n}\n\nfunction beatScale(phase: number, beatMs: number): number {\n if (phase < BEAT_POP_IN_MS) {\n return Math.min(1, 0.92 + 0.08 * easeOutBack(phase / BEAT_POP_IN_MS));\n }\n const holdEnd = beatMs - BEAT_POP_OUT_MS;\n if (phase >= holdEnd) {\n return 1 - 0.06 * easeInCubic((phase - holdEnd) / BEAT_POP_OUT_MS);\n }\n return 1;\n}\n\nfunction partitionShowcase(overlays: SwirlOverlay[]): {\n persistent: SwirlOverlay[];\n beats: SwirlOverlay[][];\n} {\n const visible = overlays.filter((o) => o.visible);\n const persistent: SwirlOverlay[] = [];\n const spotlight: SwirlOverlay[] = [];\n for (const o of visible) {\n if (SHOWCASE_PERSISTENT_TYPES.has(o.type)) persistent.push(o);\n else spotlight.push(o);\n }\n spotlight.sort(\n (a, b) => (a.z_index - b.z_index) || (a.id - b.id)\n );\n const beats: SwirlOverlay[][] = [];\n for (const o of spotlight) beats.push([o]);\n return { persistent, beats };\n}\n\nfunction useShowcaseBeat(\n enabled: boolean,\n cycleMs: number,\n beats: number\n): { beatIndex: number; beatPhase: number; beatMs: number } {\n const safeBeats = Math.max(1, beats);\n const beatMs = Math.max(\n SHOWCASE_MIN_BEAT_MS,\n Math.floor(cycleMs / safeBeats)\n );\n const totalMs = beatMs * safeBeats;\n const [now, setNow] = useState<number>(() => Date.now());\n useEffect(() => {\n if (!enabled) return;\n const id = window.setInterval(() => setNow(Date.now()), 64);\n return () => clearInterval(id);\n }, [enabled]);\n const phase = now % totalMs;\n const beatIndex = Math.min(safeBeats - 1, Math.floor(phase / beatMs));\n const beatPhase = phase - beatIndex * beatMs;\n return { beatIndex, beatPhase, beatMs };\n}\n\nexport const OverlayRenderer: React.FC<OverlayRendererProps> = ({\n overlays,\n currentTime,\n videoRef,\n coordinateSpace,\n showcaseMode = false,\n showcaseCycleMs = SHOWCASE_CYCLE_MS_DEFAULT,\n}) => {\n const [dims, setDims] = useState<VideoDimensions | null>(null);\n const rafRef = useRef<number | null>(null);\n const [fadeMap, setFadeMap] = useState<Map<number, OverlayFadeState>>(new Map());\n const removeTimers = useRef<Map<number, ReturnType<typeof setTimeout>>>(new Map());\n\n const mountTimeRef = useRef<number>(Date.now());\n const [wallclockSec, setWallclockSec] = useState<number>(0);\n useEffect(() => {\n if (!showcaseMode) return;\n const tick = () =>\n setWallclockSec((Date.now() - mountTimeRef.current) / 1000);\n tick();\n const id = window.setInterval(tick, 200);\n return () => clearInterval(id);\n }, [showcaseMode]);\n\n const { persistent: showcasePersistent, beats: showcaseBeats } = useMemo(\n () => partitionShowcase(overlays),\n [overlays]\n );\n const {\n beatIndex: showcaseBeatIndex,\n beatPhase: showcaseBeatPhase,\n beatMs: showcaseBeatMs,\n } = useShowcaseBeat(showcaseMode, showcaseCycleMs, showcaseBeats.length);\n\n const showcasePersistentIds = useMemo(\n () => new Set(showcasePersistent.map((o) => o.id)),\n [showcasePersistent]\n );\n const showcaseSpotlightIds = useMemo(() => {\n const beat = showcaseBeats[showcaseBeatIndex];\n return new Set((beat ?? []).map((o) => o.id));\n }, [showcaseBeats, showcaseBeatIndex]);\n\n const updateDims = useCallback(() => {\n const video = videoRef.current;\n if (video) {\n const computed = computeVideoDimensions(video);\n setDims((prev) => {\n if (\n !computed ||\n (prev &&\n prev.nativeWidth === computed.nativeWidth &&\n prev.nativeHeight === computed.nativeHeight &&\n prev.displayWidth === computed.displayWidth &&\n prev.displayHeight === computed.displayHeight &&\n prev.offsetX === computed.offsetX &&\n prev.offsetY === computed.offsetY)\n ) {\n return prev;\n }\n return computed;\n });\n }\n }, [videoRef]);\n\n useEffect(() => {\n updateDims();\n const interval = setInterval(updateDims, 500);\n\n const handleResize = () => {\n if (rafRef.current) cancelAnimationFrame(rafRef.current);\n rafRef.current = requestAnimationFrame(updateDims);\n };\n window.addEventListener(\"resize\", handleResize);\n\n return () => {\n clearInterval(interval);\n window.removeEventListener(\"resize\", handleResize);\n if (rafRef.current) cancelAnimationFrame(rafRef.current);\n };\n }, [updateDims]);\n\n const activeOverlays = useMemo(() => {\n if (showcaseMode) {\n const beat = showcaseBeats[showcaseBeatIndex] ?? [];\n const scheduledPersistent = showcasePersistent.filter((o) =>\n isOverlayActive(o, wallclockSec)\n );\n return [...scheduledPersistent, ...beat];\n }\n return overlays.filter((o) => isOverlayActive(o, currentTime));\n }, [\n overlays,\n currentTime,\n wallclockSec,\n showcaseMode,\n showcasePersistent,\n showcaseBeats,\n showcaseBeatIndex,\n ]);\n\n useLayoutEffect(() => {\n const activeIds = new Set(activeOverlays.map((o) => o.id));\n\n setFadeMap((prev) => {\n const next = new Map(prev);\n\n for (const overlay of activeOverlays) {\n if (!next.has(overlay.id)) {\n next.set(overlay.id, { overlay, visible: false });\n } else {\n const existing = next.get(overlay.id)!;\n next.set(overlay.id, { ...existing, overlay });\n }\n }\n\n for (const [id, state] of next) {\n if (!activeIds.has(id) && state.visible) {\n next.set(id, { ...state, visible: false });\n if (!removeTimers.current.has(id)) {\n const timer = setTimeout(() => {\n setFadeMap((m) => {\n const updated = new Map(m);\n updated.delete(id);\n return updated;\n });\n removeTimers.current.delete(id);\n }, FADE_DURATION_MS);\n removeTimers.current.set(id, timer);\n }\n } else if (!activeIds.has(id) && !state.visible) {\n }\n }\n\n return next;\n });\n }, [activeOverlays]);\n\n useEffect(() => {\n const toFadeIn: number[] = [];\n for (const [id, state] of fadeMap) {\n if (!state.visible) {\n const isActive = activeOverlays.some((o) => o.id === id);\n if (isActive) toFadeIn.push(id);\n }\n }\n if (toFadeIn.length === 0) return;\n\n const raf = requestAnimationFrame(() => {\n setFadeMap((prev) => {\n const next = new Map(prev);\n for (const id of toFadeIn) {\n const state = next.get(id);\n if (state) next.set(id, { ...state, visible: true });\n }\n return next;\n });\n });\n return () => cancelAnimationFrame(raf);\n }, [fadeMap, activeOverlays]);\n\n useEffect(() => {\n return () => {\n for (const timer of removeTimers.current.values()) clearTimeout(timer);\n };\n }, []);\n\n if (!dims || fadeMap.size === 0) return null;\n\n return (\n <div\n aria-hidden=\"true\"\n style={{\n position: \"absolute\",\n left: `${dims.offsetX}px`,\n top: `${dims.offsetY}px`,\n width: `${dims.displayWidth}px`,\n height: `${dims.displayHeight}px`,\n pointerEvents: \"none\",\n overflow: \"hidden\",\n zIndex: 8,\n }}\n >\n {[...fadeMap.values()].map(({ overlay, visible }) => {\n const scaleX = coordinateSpace?.width\n ? dims.displayWidth / coordinateSpace.width\n : dims.scaleX;\n const scaleY = coordinateSpace?.height\n ? dims.displayHeight / coordinateSpace.height\n : dims.scaleY;\n const left = overlay.x * scaleX;\n const top = overlay.y * scaleY;\n const width = overlay.width * scaleX;\n const height = overlay.height * scaleY;\n const baseOpacity = Math.max(0, Math.min(100, overlay.opacity)) / 100;\n const isShowcasePersistent =\n showcaseMode && showcasePersistentIds.has(overlay.id);\n const isShowcaseSpotlight =\n showcaseMode && showcaseSpotlightIds.has(overlay.id);\n\n const isShowcaseDormant =\n showcaseMode && !isShowcasePersistent && !isShowcaseSpotlight;\n const useShowcasePop = isShowcaseSpotlight;\n const opacity = useShowcasePop\n ? baseOpacity *\n beatOpacity(showcaseBeatPhase, showcaseBeatMs)\n : isShowcaseDormant\n ? 0\n : visible\n ? baseOpacity\n : 0;\n const popScale = useShowcasePop\n ? beatScale(showcaseBeatPhase, showcaseBeatMs)\n : 1;\n const sz: OverlaySize = { w: width, h: height };\n\n const enterAnim = getEnterAnimation(overlay);\n const hasSlide = enterAnim !== \"fade\" && !useShowcasePop;\n const slideTransform = hasSlide && !visible\n ? enterHiddenTransform(enterAnim)\n : \"\";\n const popTransform = showcaseMode && useShowcasePop\n ? `scale(${popScale})`\n : \"\";\n const combinedTransform = [slideTransform, popTransform]\n .filter(Boolean)\n .join(\" \");\n\n return (\n <div\n key={overlay.id}\n style={{\n position: \"absolute\",\n left: `${left}px`,\n top: `${top}px`,\n width: `${width}px`,\n height: `${height}px`,\n opacity,\n transition: useShowcasePop\n ? \"none\"\n : hasSlide\n ? `opacity ${FADE_DURATION_MS}ms ease, transform ${FADE_DURATION_MS}ms cubic-bezier(0.22, 1, 0.36, 1)`\n : `opacity ${FADE_DURATION_MS}ms ease`,\n transform: combinedTransform || undefined,\n transformOrigin: showcaseMode && useShowcasePop ? \"center center\" : undefined,\n zIndex: overlay.z_index,\n overflow: \"hidden\",\n }}\n >\n {overlay.type === \"image\" && <ImageOverlay overlay={overlay} />}\n {overlay.type === \"text\" && <TextOverlay overlay={overlay} />}\n {overlay.type === \"scroller\" && <ScrollerOverlay overlay={overlay} />}\n {overlay.type === \"shape\" && <ShapeOverlay overlay={overlay} size={sz} />}\n {overlay.type === \"score_bug\" && <ScoreBugOverlay overlay={overlay} size={sz} />}\n {overlay.type === \"lower_third\" && <LowerThirdOverlay overlay={overlay} size={sz} />}\n {overlay.type === \"qr_code\" && <QrCodeOverlay overlay={overlay} size={sz} />}\n {overlay.type === \"coming_up_next\" && <ComingUpNextOverlay overlay={overlay} size={sz} />}\n {overlay.type === \"contextual_trigger\" && <ContextualTriggerOverlay overlay={overlay} size={sz} />}\n {overlay.type === \"odds_betting\" && <OddsBettingOverlay overlay={overlay} size={sz} />}\n {overlay.type === \"breaking_news\" && <BreakingNewsOverlay overlay={overlay} size={sz} />}\n {overlay.type === \"countdown\" && <CountdownOverlay overlay={overlay} size={sz} />}\n </div>\n );\n })}\n </div>\n );\n};\n","export const OVERLAY_API_BASE = \"https://adstorm.co/api-adstorm-dev\";\n\nexport interface OverlayCoordinateSpace {\n width: number;\n height: number;\n}\n\nexport interface SwirlScrollerConfig {\n rss_url?: string;\n update_interval?: number;\n scroll_speed?: number;\n direction?: string;\n font_size?: number;\n font_family?: string;\n font_weight?: string;\n text_color?: string;\n background_color?: string;\n background_opacity?: number;\n border_color?: string;\n border_width?: number;\n border_radius?: number;\n padding?: number;\n margin?: number;\n show_title?: boolean;\n show_description?: boolean;\n show_timestamp?: boolean;\n show_author?: boolean;\n show_category?: boolean;\n max_items?: number;\n item_spacing?: number;\n fade_in_out?: boolean;\n fade_distance?: number;\n auto_refresh?: boolean;\n use_custom_text?: boolean;\n custom_text?: string;\n label?: string;\n label_line2?: string;\n label_color?: string;\n label_text_color?: string;\n accent_color?: string;\n show_accent_line?: boolean;\n separator_char?: string;\n preset?: string;\n}\n\nexport type SwirlOverlayType =\n | \"image\"\n | \"text\"\n | \"scroller\"\n | \"shape\"\n | \"score_bug\"\n | \"lower_third\"\n | \"qr_code\"\n | \"coming_up_next\"\n | \"contextual_trigger\"\n | \"odds_betting\"\n | \"breaking_news\"\n | \"countdown\";\n\nexport interface SwirlOverlay {\n id: number;\n project_id: number;\n name: string;\n type: SwirlOverlayType | string;\n visible: boolean;\n x: number;\n y: number;\n width: number;\n height: number;\n opacity: number;\n start_time: string;\n duration: string;\n content?: string;\n image_url?: string;\n scroller_config?: SwirlScrollerConfig;\n z_index: number;\n created_at?: string;\n updated_at?: string;\n}\n\nexport function timeStringToSeconds(timeStr: string): number {\n if (!timeStr) return 0;\n\n const parts = timeStr.split(\":\");\n\n if (parts.length >= 3) {\n const hours = parseInt(parts[0] ?? \"0\", 10) || 0;\n const minutes = parseInt(parts[1] ?? \"0\", 10) || 0;\n const secStr = parts[2] ?? \"0\";\n const dotIdx = secStr.indexOf(\".\");\n const seconds =\n parseInt(dotIdx >= 0 ? secStr.substring(0, dotIdx) : secStr, 10) || 0;\n const msFrag = dotIdx >= 0 ? secStr.substring(dotIdx + 1) : \"\";\n const ms = msFrag ? parseInt(msFrag.padEnd(3, \"0\").substring(0, 3), 10) || 0 : 0;\n return hours * 3600 + minutes * 60 + seconds + ms / 1000;\n }\n\n if (parts.length === 2) {\n const minutes = parseInt(parts[0] ?? \"0\", 10) || 0;\n const secStr = parts[1] ?? \"0\";\n const dotIdx = secStr.indexOf(\".\");\n const seconds =\n parseInt(dotIdx >= 0 ? secStr.substring(0, dotIdx) : secStr, 10) || 0;\n const msFrag = dotIdx >= 0 ? secStr.substring(dotIdx + 1) : \"\";\n const ms = msFrag ? parseInt(msFrag.padEnd(3, \"0\").substring(0, 3), 10) || 0 : 0;\n return minutes * 60 + seconds + ms / 1000;\n }\n\n const num = parseFloat(timeStr);\n return isFinite(num) ? Math.max(0, num) : 0;\n}\n\nexport function isOverlayActive(\n overlay: SwirlOverlay,\n currentTime: number\n): boolean {\n if (!overlay.visible) return false;\n const startSec = timeStringToSeconds(overlay.start_time);\n const durationSec = timeStringToSeconds(overlay.duration);\n if (durationSec <= 0) return false;\n return currentTime >= startSec && currentTime < startSec + durationSec;\n}\n\nfunction normalizeScrollerConfig(\n raw: SwirlScrollerConfig | Record<string, unknown> | undefined\n): SwirlScrollerConfig | undefined {\n if (!raw || typeof raw !== \"object\") return undefined;\n const r = raw as Record<string, unknown>;\n const merged: SwirlScrollerConfig = { ...(raw as SwirlScrollerConfig) };\n if (merged.use_custom_text === undefined && typeof r.useCustomText === \"boolean\") {\n merged.use_custom_text = r.useCustomText;\n }\n if ((merged.custom_text === undefined || merged.custom_text === \"\") && typeof r.customText === \"string\") {\n merged.custom_text = r.customText;\n }\n if (!merged.rss_url && typeof r.rssUrl === \"string\") {\n merged.rss_url = r.rssUrl;\n }\n return merged;\n}\n\nexport function normalizeSwirlOverlay(raw: SwirlOverlay & Record<string, unknown>): SwirlOverlay {\n const o = { ...raw };\n if (o.type === \"scroller\") {\n const sc = raw.scroller_config ?? (raw as Record<string, unknown>).scrollerConfig;\n const normalized = normalizeScrollerConfig(sc as SwirlScrollerConfig);\n if (normalized) o.scroller_config = normalized;\n }\n return o;\n}\n\nexport async function fetchProjectOverlays(\n projectId: number,\n apiBaseUrl: string = OVERLAY_API_BASE\n): Promise<SwirlOverlay[]> {\n const base = apiBaseUrl.replace(/\\/$/, \"\");\n const response = await fetch(\n `${base}/adstorm/swirl/projects/${projectId}/overlays`\n );\n if (!response.ok) {\n throw new Error(\n `Failed to fetch overlays: ${response.status} ${response.statusText}`\n );\n }\n const data = await response.json();\n if (!Array.isArray(data)) return [];\n return data.map((row: SwirlOverlay & Record<string, unknown>) =>\n normalizeSwirlOverlay(row)\n );\n}\n\nexport function resolveImageUrl(\n imageUrl: string,\n apiBaseUrl: string = OVERLAY_API_BASE\n): string {\n if (!imageUrl) return \"\";\n if (imageUrl.startsWith(\"http://\") || imageUrl.startsWith(\"https://\")) {\n return imageUrl;\n }\n if (imageUrl.startsWith(\"/\")) {\n try {\n const url = new URL(apiBaseUrl);\n return `${url.origin}${imageUrl}`;\n } catch {\n return imageUrl;\n }\n }\n return `${apiBaseUrl}/${imageUrl}`;\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["/home/ubuntu24-new/Dev/stormcloud-vp/lib/ui/StormcloudVideoPlayer.cjs","../../src/ui/StormcloudVideoPlayer.tsx","../../src/player/StormcloudVideoPlayer.ts","../../src/sdk/hlsAdPlayer.ts","../../src/sdk/pal.ts","../../src/utils/tracking.ts","../../src/utils/polyfills.ts","../../src/utils/browserCompat.ts"],"names":["__create","Object","create","__defProp","defineProperty","__getOwnPropDesc","getOwnPropertyDescriptor","__getOwnPropNames","getOwnPropertyNames","__getProtoOf","getPrototypeOf","__hasOwnProp","prototype","hasOwnProperty","__export","target","all","name","get","enumerable","__copyProps","to","from","except","desc","key","call","__toESM","mod","isNodeMode","__esModule","value","__toCommonJS","StormcloudVideoPlayer_exports","StormcloudVideoPlayerComponent","module","exports","import_react","require","import_hls","createHlsAdPlayer","contentVideo","options","adPlaying","originalMutedState","originalVolume","Math","max","min","volume","listeners","Map","licenseKey","mainHlsInstance","adVideoElement","adHls","adContainerEl","currentAd","sessionId","preloadedAds","preloadingAds","destroyed","pendingTimeouts","trackingFired","impression","start","firstQuartile","midpoint","thirdQuartile","complete","emit","event","payload","set","Array","fn","error","console","warn","fireTrackingPixels","generateSessionId","Date","now","random","toString","substr","urls","length","forEach","url","trackingUrl","includes","img","Image","log","getMainStreamQuality","levels","currentLevel","autoLevel","loadLevel","level","width","height","bitrate","selectBestMediaFile","mediaFiles","mediaFile","type","Error","firstFile","mainQuality","scoredFiles","map","file","widthDiff","abs","heightDiff","resolutionDiff","fileBitrate","bitrateDiff","score","sort","a","b","bestMatch","resolution","isHlsMediaFile","toLowerCase","isProgressiveMediaFile","startsWith","endsWith","parseVastXml","xmlString","xmlDoc","parser","DOMParser","parseFromString","parserError","querySelector","textContent","adElement","adId","getAttribute","title","isNoAdAvailable","durationText","durationParts","split","duration","parseInt","mediaFileElements","querySelectorAll","mf","index","trim","bitrateAttr","bitrateValue","push","trackingUrls","mute","unmute","pause","resume","fullscreen","exitFullscreen","skip","el","eventKey","clickThrough","id","fetchAndParseVastAd","vastTagUrl","response","vastXml","fetch","mode","credentials","headers","referrerPolicy","ok","statusText","text","substring","createAdVideoElement","video","document","createElement","style","position","left","top","objectFit","backgroundColor","playsInline","muted","setupAdEventListeners","addEventListener","progress","handleAdComplete","e","handleAdError","ended","currentTime","setAdPlayingFlag","isPlaying","dataset","stormcloudAdPlaying","display","pointerEvents","paused","play","catch","initialize","container","right","bottom","alignItems","justifyContent","zIndex","parentElement","appendChild","has","ad","Promise","reject","resolve","contentVolume","adVolume","isHlsAd","continueLiveStreamDuringAds","Hls","isSupported","destroy","enableWorker","lowLatencyMode","loadSource","attachMedia","on","Events","MANIFEST_PARSED","ERROR","data","fatal","canPlayType","src","load","stop","previousMutedState","visibility","opacity","timeoutId","clearTimeout","remove","removeChild","clear","isAdPlaying","resize","listener","off","add","delete","updateOriginalMutedState","nextVolume","Number","isNaN","getOriginalMutedState","getOriginalVolume","getAdVolume","hidePlaceholder","PAL_SDK_URL","_nonceLoader","_palLoadPromise","window","goog","timeout","pal","setTimeout","existing","script","async","setAttribute","onload","onerror","head","getOrCreateNonceLoader","consentSettings","ConsentSettings","allowStorage","NonceLoader","createPalNonceManager","currentNonce","currentNonceManager","generateNonce","loader","request","manager","loadPalSdk","NonceRequest","adWillAutoPlay","adWillPlayMuted","continuousPlayback","descriptionUrl","location","href","iconsSupported","playerType","playerVersion","supportedApiFrameworks","videoWidth","videoHeight","ppid","loadNonceManager","getNonce","getCurrentNonce","injectNonce","URL","searchParams","base","replace","sep","encodeURIComponent","sendPlaybackStart","sendPlaybackEnd","sendAdClick","sendAdTouch","reset","cachedBrowserId","getClientInfo","screen","navigator","ua","userAgent","platform","vendor","maxTouchPoints","memory","deviceMemory","hardwareConcurrency","screenInfo","availWidth","availHeight","orientation","pixelDepth","deviceType","brand","os","model","isSmartTV","isAndroid","isWebView","isWebApp","webosMatch","match","tizenMatch","tvMatch","test","androidModelMatch","outerHeight","outerWidth","matchMedia","matches","standalone","angle","domain","hostname","origin","path","pathname","language","languages","join","cookieEnabled","doNotTrack","referrer","visibilityState","getBrowserID","clientInfo","fingerprintString","encodedData","utf8","buffer","i","hashBuffer","hashArray","hashHex","hash","char","fallbackHash","timestamp","JSON","stringify","crypto","subtle","digest","Uint8Array","TextEncoder","encode","unescape","charCodeAt","padStart","padEnd","PLAYER_TRACKING_BASE_URL","TRACK_URL","HEARTBEAT_URL","IMPRESSIONS_URL","buildHeaders","sendTrackRequest","body","method","status","json","postJson","buildPlayerMetricEvent","player_id","license_key","context","flags","browserId","captureAt","toISOString","device_type","input_stream_type","inputStreamType","ad_loaded","adLoaded","ad_detect","adDetect","capture_at","trackingData","events","sendHeartbeat","adDetectInfo","sendAdLoadedTracking","adLoadedInfo","sendAdImpressionTracking","adImpressionInfo","metricEvent","ad_played_count","ad_url","adUrl","heartbeatData","polyfillURLSearchParams","URLSearchParams","URLSearchParamsPolyfill","init","params","parseQueryString","append","query","cleanQuery","slice","param","decodedKey","safeDecodeURIComponent","decodedValue","str","decodeURIComponent","values","String","getAll","callback","parts","polyfillTextEncoder","TextEncoderPolyfill","encoding","charcode","polyfillPromiseFinally","finally","constructor","then","reason","polyfillObjectAssign","assign","sources","TypeError","nextSource","nextKey","polyfillArrayFrom","arrayLike","mapFn","thisArg","items","len","result","polyfillStringStartsWith","search","pos","polyfillStringEndsWith","polyfillStringIncludes","indexOf","initializePolyfills","getChromeVersion","getWebKitVersion","getPlatform","userAgentData","detectBrowser","version","majorVersion","isLegacyTV","supportsModernJS","webOSVersion","tizenVersion","chromeVersionNum","chromeVersion","webkitVersion","Set","getBrowserConfigOverrides","browser","overrides","allowNativeHls","logBrowserInfo","debug","StormcloudVideoPlayer","config","attached","inAdBreak","ptsDriftEmaMs","adPodQueue","vmapBreaks","consumedVmapBreakIds","lastHeartbeatTime","currentAdIndex","totalAdsInBreak","showAds","isLiveStream","nativeHlsMode","videoSrcProtection","bufferedSegmentsCount","shouldAutoplayAfterBuffering","hasInitialBufferCompleted","adRequestTokenCounter","activeAdRequestToken","adRequestWatchdogToken","adFailsafeToken","failedVastUrls","temporaryFailureUrls","temporaryFailureCooldownMs","continuousFetchingActive","adRequestQueue","maxPlaceholderDurationMs","isShowingPlaceholder","tsScte35Pids","pmtPids","processedTsScte35Sections","pendingScte35Cues","recentScte35CueKeys","recentScte35CueLimit","totalAdRequestsInBreak","maxTotalAdRequestsPerBreak","pendingAdBreak","consecutiveFailures","maxConsecutiveFailures","lastAdRequestTime","minAdRequestIntervalMs","backoffBaseMs","maxBackoffMs","globalConsecutiveNoFills","globalNoFillThreshold","globalNoFillCooldownUntil","globalNoFillBackoffBaseMs","globalNoFillBackoffMaxMs","globalLastGamRequestTime","globalMinGamIntervalMs","preloadPool","maxPreloadPoolSize","preloadPoolActive","preloadPoolLoopRunning","adDetectSentForCurrentBreak","palPlaybackStarted","continuousFetchLoopRunning","browserOverrides","videoElement","debugAdTiming","adPlayer","createAdPlayer","palNonce","hls","attach","fetchAdConfiguration","offsetHeight","clientHeight","autoplay","initializeTracking","shouldUseNativeHls","isLive","adBehavior","import_hls2","backBufferLength","liveDurationInfinity","maxLiveSyncPlaybackRate","liveSyncDuration","maxBufferLength","maxMaxBufferLength","maxBufferSize","maxBufferHole","highBufferWatchdogPeriod","nudgeOffset","nudgeMaxRetry","startPosition","MEDIA_ATTACHED","_","minSegments","some","details","live","shouldContinueLiveStreamDuringAds","minSegmentsBeforePlay","LEVEL_LOADED","_evt","fragments","fragmentsToScan","frag","tagList","isArray","entry","tag","idx","attrs","parseAttributeList","hasScteOut","durationSeconds","parseCueOutDuration","marker","raw","earlyDetection","onScte35Cue","createScte35CueContext","FRAG_BUFFERED","err","FRAG_PARSING_METADATA","id3Tags","samples","s","ptsSeconds","pts","onId3Tag","FRAG_LOADED","processFragmentScte35Payload","sn","getFragmentStartSeconds","FRAG_DECRYPTED","FRAG_CHANGED","activatePendingScte35CuesForFragment","prog","parseCueOutCont","elapsed","hasScteIn","klass","toNumber","ErrorTypes","NETWORK_ERROR","startLoad","MEDIA_ERROR","recoverMediaError","attachImaEventListeners","source","adIndex","remaining","getRemainingAdMs","queuedUrls","tryNextAvailableAdWithRateLimit","handleAdPodComplete","errorPayload","errorMessage","errorCode","code","vastErrorCode","message","cause","innerError","causeMessage","handleAdFailure","clearAdRequestWatchdog","resetGamNoFillCounter","expectedAdBreakDurationMs","adStopTimerId","scheduleAdStopCountdown","currentMuted","currentVolume","setAdVolume","clearAdFailsafeTimer","recreateAdController","shouldShowPlaceholder","showPlaceholderLayer","showPlaceholder","preservedMutedState","preservedVolumeState","ensurePlaceholderContainer","placeholderContainer","transition","wasHidden","requestAnimationFrame","hidePlaceholderLayer","timeUpdateHandler","onTimeUpdate","emptiedHandler","wasPaused","streamType","canNative","parseScte35FromId3","readiness","decodeId3ValueToText","cueOutMatch","arg","dur","id3","cueOutContMatch","cont","cueInMatch","daterangeMatch","bin","parseScte35Binary","decoder","TextDecoder","out","fromCharCode","fragmentSn","fragmentStartSeconds","startPTS","candidates","candidate","isFinite","cue","createScte35Cue","pendingKey","getPendingScte35CueKey","startAdPrefetch","shouldAcceptScte35EndCue","activeScte35BreakKey","hasRecentlyHandledScte35Cue","markScte35CueHandled","onScte35Marker","getScte35CueKey","getScte35MarkerRaw","spliceEventId","toIdentityString","splice_event_id","segmentationEventId","segmentation_event_id","daterangeId","ID","scteValue","round","floor","isStrongScte35CueKey","scheduledScte35BreakKey","recentKey","trimRecentScte35CueMaps","size","firstKey","keys","next","matchingCues","entries","filter","cueKey","newDurationMs","elapsedMs","currentAdBreakStartWallClockMs","remainingMs","detectPayload","sendAdDetectTracking","hasPrefetchedAds","vastUrls","durationMs","isManifestMarker","isManifestBasedMarker","forceImmediate","immediateManifestAds","hasPts","clearAdStartTimer","startScte35AdBreak","tol","driftToleranceMs","nowMs","estCurrentPtsMs","deltaMs","tolerance","markerPtsMs","scheduleAdStartIn","hasQueuedAds","activeAdRequest","clearAdStopTimer","res","pendingScte35CueKey","handleAdStart","num","parseFloat","dStr","d","elapsedMatch","durationMatch","slashMatch","regex","exec","rawVal","val","n","splice_command_type","normalizeFragmentPayload","ArrayBuffer","isView","view","byteOffset","byteLength","payloadData","markers","parseScte35FromTsPackets","packetInfo","detectTsPacketFormat","sectionAssemblers","packetStart","offset","packetSize","tsStart","tsPayloadOffset","secondByte","thirdByte","fourthByte","payloadUnitStart","pid","adaptationFieldControl","hasPayload","payloadStart","adaptationLength","payloadEnd","parsePatSection","parsePmtSection","collectScte35SectionsFromPayload","packetSizes","matchedPackets","sectionStart","getPsiSectionStart","sectionLength","getPsiSectionLength","sectionEnd","programNumber","programInfoLength","elementaryPid","esInfoLength","descriptorEnd","descriptorStart","descriptorsIdentifyScte35","end","assemblers","expectedLength","registration","pointerField","previousAssembler","appendScte35Bytes","subarray","tableId","totalLength","addScte35SectionMarker","bytes","assembler","section","hasProcessedTsScte35Section","buf","BitReader","checksum","bytePos","bitPos","readBits","numBits","remainingInByte","toRead","currentByte","shift","mask","bits","skipBits","bytePosition","readSpliceTime","r","ptsAdjustmentTicks","timeSpecifiedFlag","high","ptsTicks","low","ptsAdjHigh","ptsAdjLow","spliceCommandLength","spliceCommandType","markerType","commandBodyStart","cancel","outOfNetwork","programSpliceFlag","durationFlag","spliceImmediateFlag","componentCount","componentPtsSeconds","durationTicks","expectedDescriptorOffset","descriptorMarker","parseScte35SegmentationDescriptors","descriptorLoopLength","descriptorOffset","descriptorTag","descriptorLength","descriptorDataStart","descriptorDataEnd","parseScte35SegmentationDescriptor","descriptor","cancelIndicator","identifier","programSegmentationFlag","segmentationDurationFlag","segmentationUpidLength","segmentationTypeId","markerTypeFromSegmentationTypeId","sendInitialTracking","heartbeatInterval","setInterval","sendHeartbeatIfNeeded","vastMode","vastEndpoint","apiUrl","imaPayload","numberAds","vmapUrl","fetchAndParseVmap","apiVastTagUrl","adBreakNodes","timeOffsetRaw","node","parsed","parseVmapTimeOffsetToMs","timeOffset","ima","vast","cue_tones","number_ads","apiNumberAds","vmapXml","parseVmapToBreaks","doc","startTimeMs","adTagNode","adTagUrl","breakId","aStart","MAX_SAFE_INTEGER","bStart","normalized","hms","hh","mm","ss","ms","hours","minutes","seconds","millis","percent","ratio","durationSec","getAdBreakKey","adBreak","resolveBreakStartMs","getCurrentAdIndex","getTotalAdsInBreak","getAdRemainingMs","generateVastUrlsWithCorrelators","baseUrl","count","baseTimestamp","uniqueCorrelator","urlWithCorrelator","correlatorRegex","isShowingAds","getStreamType","shouldShowNativeControls","showCustomControls","scheduled","findCurrentOrNextBreak","tags","selectVastTagsForBreak","baseVastUrl","urlsToPregenerate","generatedUrls","detectedAtFragmentSn","isFetching","fetchStartTime","clearPendingAdBreak","prefetchTimerId","startPreloadPool","initialUrls","preloadAdIntoPool","preloadPoolLoop","vastUrl","loadPromise","isGamInCooldown","isUrlInCooldown","hasAdError","adErrorPayload","errorListenerCleanup","preloadAd","errorListener","isNoFill","poolEntry","lateErrorListener","enforceGlobalRateLimit","requestAds","recordGamNoFill","isTemporaryAdError","adController","loadedAt","isReady","findIndex","splice","newUrls","newUrl","getPreloadedAd","stopPreloadPool","_marker","adBreakDurationMs","firstAdUrl","usePreloadedAd","preloadedController","preloaded","firstAdUrlArray","fallbackPreloaded","fallbackError","startContinuousFetching","continuousFetchLoop","newAdUrl","queuedUrlsPreview","generationDelay","pow","stopContinuousFetching","backoffMultiplier","backoffDelay","effectiveMinInterval","timeSinceLastRequest","waitTime","tryNextAvailableAd","retryCount","nextAdUrl","maxRetries","cleanupTemporaryFailures","playSingleAd","showPlaceholderAndWaitForAds","checkInterval","maxChecks","schedule","breakStartMs","currentTimeSec","findBreakForTime","handleMidAdJoin","breakToPlay","endMs","inWindow","first","rest","ensureAdStoppedByTimer","checkIntervalMs","adBreakCheckIntervalMs","maxExtensionMsConfig","maxAdBreakExtensionMs","elapsedSinceStartMs","expectedDurationMs","shouldExtendAdBreak","pendingAds","overrunMs","maxExtensionMs","delayMs","adStartTimerId","updatePtsDrift","ptsSecondsSample","sampleMs","alpha","failureTime","exponent","backoff"],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;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AAA,CAAKoJ,0BAAA,EAA4B;8BACtD,IAAA,CAAKD,oBAAA,CAAqBnR,MAAA,CAAO3K;0BACnC;sBACF;;sBAJA;sBAAA;;;+BAAA,6BAAA;4BAAA;;;;;;oCAAA;wCAAA;;;;;;;;;;;;;;;;;;cAKF;;;YAEQw4B,KAAAA;;;6BAAAA,KAAAA,0IAAAA;oBAAAA;sBACN,GAAA,CAAA,GAAOh5B,GAAAA,GAAKC,EAAAA,CAAA,KAAQ,GAAA,CAAA,CAAK4d,KAAAA,EAAAA,mBAAA;oBAC3B,GAAA;;;;;;;;;;;;;;;;;YAEQ+b,KAAAA;iBAAAA,SAAAA;gBAGN,IAAI,IAAA,CAAKjc,wBAAA,IAA4B,IAAA,CAAKC,GAAAA,kBAAA,EAAuB;oBAC/D,GAAA,CAAMqgB,WAAW,IAAA,CAAKtgB,wBAAA,GAA2B,IAAA,CAAKC,qBAAA;sDACtD,IAAMsgB,UAAUrgC,KAAKE,GAAA,CACnB,IAAA,CAAK+f,yBAAA,GAA4BjgB,KAAKw9B,GAAA,CAAI,GAAG4C,WAC7C,IAAA,CAAKlgB,wBAAA;qBAEP,IAAA,CAAKF,yBAAA,GAA4B7d,KAAKC,GAAA,KAAQi+B","sourcesContent":["\"use strict\";\nvar __create = Object.create;\nvar __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __getProtoOf = Object.getPrototypeOf;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(\n // If the importer is in node compatibility mode or this is not an ESM\n // file that has been converted to a CommonJS file using a Babel-\n // compatible transform (i.e. \"__esModule\" has not been set), then set\n // \"default\" to the CommonJS \"module.exports\" for node compatibility.\n isNodeMode || !mod || !mod.__esModule ? __defProp(target, \"default\", { value: mod, enumerable: true }) : target,\n mod\n));\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\n\n// src/ui/StormcloudVideoPlayer.tsx\nvar StormcloudVideoPlayer_exports = {};\n__export(StormcloudVideoPlayer_exports, {\n StormcloudVideoPlayerComponent: () => StormcloudVideoPlayerComponent\n});\nmodule.exports = __toCommonJS(StormcloudVideoPlayer_exports);\nvar import_react = __toESM(require(\"react\"), 1);\n\n// src/player/StormcloudVideoPlayer.ts\nvar import_hls2 = __toESM(require(\"hls.js\"), 1);\n\n// src/sdk/hlsAdPlayer.ts\nvar import_hls = __toESM(require(\"hls.js\"), 1);\nfunction createHlsAdPlayer(contentVideo, options) {\n let adPlaying = false;\n let originalMutedState = false;\n let originalVolume = Math.max(0, Math.min(1, contentVideo.volume || 1));\n const listeners = /* @__PURE__ */ new Map();\n const licenseKey = options?.licenseKey;\n const mainHlsInstance = options?.mainHlsInstance;\n let adVideoElement;\n let adHls;\n let adContainerEl;\n let currentAd;\n let sessionId;\n const preloadedAds = /* @__PURE__ */ new Map();\n const preloadingAds = /* @__PURE__ */ new Map();\n let destroyed = false;\n let pendingTimeouts = [];\n let trackingFired = {\n impression: false,\n start: false,\n firstQuartile: false,\n midpoint: false,\n thirdQuartile: false,\n complete: false\n };\n function emit(event, payload) {\n const set = listeners.get(event);\n if (!set) return;\n for (const fn of Array.from(set)) {\n try {\n fn(payload);\n } catch (error) {\n console.warn(\n `[HlsAdPlayer] Error in event listener for ${event}:`,\n error\n );\n }\n }\n }\n function generateSessionId() {\n return `session-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;\n }\n function fireTrackingPixels(urls) {\n if (!urls || urls.length === 0) return;\n urls.forEach((url) => {\n try {\n let trackingUrl = url;\n if (sessionId) {\n trackingUrl = `${trackingUrl}${trackingUrl.includes(\"?\") ? \"&\" : \"?\"}session_id=${sessionId}`;\n }\n if (licenseKey) {\n trackingUrl = `${trackingUrl}${trackingUrl.includes(\"?\") ? \"&\" : \"?\"}license_key=${licenseKey}`;\n }\n const img = new Image(1, 1);\n img.src = trackingUrl;\n console.log(`[HlsAdPlayer] Fired tracking pixel: ${trackingUrl}`);\n } catch (error) {\n console.warn(`[HlsAdPlayer] Error firing tracking pixel:`, error);\n }\n });\n }\n function getMainStreamQuality() {\n if (!mainHlsInstance || !mainHlsInstance.levels) {\n return null;\n }\n const currentLevel = mainHlsInstance.currentLevel;\n if (currentLevel === -1 || !mainHlsInstance.levels[currentLevel]) {\n const autoLevel = mainHlsInstance.loadLevel;\n if (autoLevel !== -1 && mainHlsInstance.levels[autoLevel]) {\n const level2 = mainHlsInstance.levels[autoLevel];\n return {\n width: level2.width || 1920,\n height: level2.height || 1080,\n bitrate: level2.bitrate || 5e6\n };\n }\n return null;\n }\n const level = mainHlsInstance.levels[currentLevel];\n return {\n width: level.width || 1920,\n height: level.height || 1080,\n bitrate: level.bitrate || 5e6\n };\n }\n function selectBestMediaFile(mediaFiles) {\n if (mediaFiles.length === 0) {\n throw new Error(\"No media files available\");\n }\n const firstFile = mediaFiles[0];\n if (!firstFile) {\n throw new Error(\"No media files available\");\n }\n if (mediaFiles.length === 1) {\n return firstFile;\n }\n const mainQuality = getMainStreamQuality();\n if (!mainQuality) {\n console.log(\n \"[HlsAdPlayer] No main stream quality info, using first media file\"\n );\n return firstFile;\n }\n console.log(\"[HlsAdPlayer] Main stream quality:\", mainQuality);\n const scoredFiles = mediaFiles.map((file) => {\n const widthDiff = Math.abs(file.width - mainQuality.width);\n const heightDiff = Math.abs(file.height - mainQuality.height);\n const resolutionDiff = widthDiff + heightDiff;\n const fileBitrate = (file.bitrate || 5e3) * 1e3;\n const bitrateDiff = Math.abs(fileBitrate - mainQuality.bitrate);\n const score = resolutionDiff * 2 + bitrateDiff / 1e3;\n return { file, score, resolutionDiff, bitrateDiff };\n });\n scoredFiles.sort((a, b) => a.score - b.score);\n const bestMatch = scoredFiles[0];\n if (!bestMatch) {\n console.log(\"[HlsAdPlayer] No best match found, using first media file\");\n return firstFile;\n }\n console.log(\"[HlsAdPlayer] Selected media file:\", {\n url: bestMatch.file.url,\n resolution: `${bestMatch.file.width}x${bestMatch.file.height}`,\n bitrate: bestMatch.file.bitrate,\n score: bestMatch.score,\n resolutionDiff: bestMatch.resolutionDiff,\n bitrateDiff: bestMatch.bitrateDiff\n });\n return bestMatch.file;\n }\n function isHlsMediaFile(mediaFile) {\n const type = mediaFile.type.toLowerCase();\n const url = mediaFile.url.toLowerCase();\n return type === \"application/x-mpegurl\" || type === \"application/vnd.apple.mpegurl\" || type.includes(\"mpegurl\") || url.includes(\".m3u8\");\n }\n function isProgressiveMediaFile(mediaFile) {\n const type = mediaFile.type.toLowerCase();\n const url = mediaFile.url.toLowerCase();\n return type.startsWith(\"video/\") || url.endsWith(\".mp4\") || url.includes(\".mp4?\");\n }\n function parseVastXml(xmlString) {\n try {\n const parser = new DOMParser();\n const xmlDoc = parser.parseFromString(xmlString, \"text/xml\");\n const parserError = xmlDoc.querySelector(\"parsererror\");\n if (parserError) {\n console.error(\n \"[HlsAdPlayer] XML parsing error (malformed VAST XML):\",\n parserError.textContent\n );\n return null;\n }\n const adElement = xmlDoc.querySelector(\"Ad\");\n if (!adElement) {\n console.warn(\"[HlsAdPlayer] No Ad element found in VAST XML\");\n return null;\n }\n const adId = adElement.getAttribute(\"id\") || \"unknown\";\n const title = xmlDoc.querySelector(\"AdTitle\")?.textContent || \"Ad\";\n const isNoAdAvailable = adId === \"empty\" || title.toLowerCase().includes(\"no ad available\") || title.toLowerCase() === \"no ad available\";\n const durationText = xmlDoc.querySelector(\"Duration\")?.textContent || \"00:00:30\";\n const durationParts = durationText.split(\":\");\n const duration = parseInt(durationParts[0] || \"0\", 10) * 3600 + parseInt(durationParts[1] || \"0\", 10) * 60 + parseInt(durationParts[2] || \"0\", 10);\n const mediaFileElements = xmlDoc.querySelectorAll(\"MediaFile\");\n const mediaFiles = [];\n console.log(\n `[HlsAdPlayer] Found ${mediaFileElements.length} MediaFile element(s) in VAST XML`\n );\n mediaFileElements.forEach((mf, index) => {\n const type = mf.getAttribute(\"type\") || \"\";\n const url = mf.textContent?.trim() || \"\";\n const width = mf.getAttribute(\"width\") || \"\";\n const height = mf.getAttribute(\"height\") || \"\";\n console.log(\n `[HlsAdPlayer] MediaFile ${index}: type=\"${type}\", url=\"${url}\", width=\"${width}\", height=\"${height}\"`\n );\n const mediaFile = {\n url,\n type,\n width: parseInt(width || \"1920\", 10),\n height: parseInt(height || \"1080\", 10),\n bitrate: void 0\n };\n if (!url) {\n console.warn(`[HlsAdPlayer] MediaFile ${index} has empty URL`);\n return;\n }\n const bitrateAttr = mf.getAttribute(\"bitrate\");\n const bitrateValue = bitrateAttr ? parseInt(bitrateAttr, 10) : void 0;\n mediaFile.bitrate = bitrateValue && bitrateValue > 0 ? bitrateValue : void 0;\n if (isHlsMediaFile(mediaFile) || isProgressiveMediaFile(mediaFile)) {\n mediaFiles.push(mediaFile);\n console.log(\n `[HlsAdPlayer] Added ${isHlsMediaFile(mediaFile) ? \"HLS\" : \"progressive\"} MediaFile: ${url}`\n );\n } else {\n console.log(\n `[HlsAdPlayer] MediaFile ${index} ignored (type=\"${type}\" is not supported)`\n );\n }\n });\n if (mediaFiles.length === 0) {\n if (isNoAdAvailable) {\n console.warn(\n \"[HlsAdPlayer] No ads available (VAST response indicates no ads)\"\n );\n } else {\n console.warn(\"[HlsAdPlayer] No supported media files found in VAST XML\");\n }\n return null;\n }\n const trackingUrls = {\n impression: [],\n start: [],\n firstQuartile: [],\n midpoint: [],\n thirdQuartile: [],\n complete: [],\n mute: [],\n unmute: [],\n pause: [],\n resume: [],\n fullscreen: [],\n exitFullscreen: [],\n skip: [],\n error: []\n };\n xmlDoc.querySelectorAll(\"Impression\").forEach((el) => {\n const url = el.textContent?.trim();\n if (url) trackingUrls.impression.push(url);\n });\n xmlDoc.querySelectorAll(\"Tracking\").forEach((el) => {\n const event = el.getAttribute(\"event\");\n const url = el.textContent?.trim();\n if (event && url) {\n const eventKey = event;\n if (trackingUrls[eventKey]) {\n trackingUrls[eventKey].push(url);\n }\n }\n });\n const clickThrough = xmlDoc.querySelector(\"ClickThrough\")?.textContent?.trim();\n return {\n id: adId,\n title,\n duration,\n mediaFiles,\n trackingUrls,\n clickThrough\n };\n } catch (error) {\n console.error(\"[HlsAdPlayer] Error parsing VAST XML:\", error);\n return null;\n }\n }\n async function fetchAndParseVastAd(vastTagUrl) {\n const response = await fetch(vastTagUrl, {\n mode: \"cors\",\n credentials: \"include\",\n headers: {\n \"Accept\": \"application/xml, text/xml, */*\"\n },\n referrerPolicy: \"no-referrer-when-downgrade\"\n });\n if (!response.ok) {\n throw new Error(`Failed to fetch VAST: ${response.statusText}`);\n }\n const vastXml = await response.text();\n console.log(\"[HlsAdPlayer] VAST XML received\");\n console.log(\n \"[HlsAdPlayer] VAST XML content (first 2000 chars):\",\n vastXml.substring(0, 2e3)\n );\n return parseVastXml(vastXml);\n }\n function createAdVideoElement() {\n const video = document.createElement(\"video\");\n video.style.position = \"absolute\";\n video.style.left = \"0\";\n video.style.top = \"0\";\n video.style.width = \"100%\";\n video.style.height = \"100%\";\n video.style.objectFit = \"contain\";\n video.style.backgroundColor = \"#000\";\n video.playsInline = true;\n video.muted = false;\n video.volume = 1;\n console.log(\n `[HlsAdPlayer] Created ad video element with volume ${video.volume}`\n );\n return video;\n }\n function setupAdEventListeners() {\n if (!adVideoElement || !currentAd) return;\n adVideoElement.addEventListener(\"timeupdate\", () => {\n if (!currentAd || !adVideoElement) return;\n const progress = adVideoElement.currentTime / currentAd.duration;\n if (progress >= 0.25 && !trackingFired.firstQuartile) {\n trackingFired.firstQuartile = true;\n fireTrackingPixels(currentAd.trackingUrls.firstQuartile);\n }\n if (progress >= 0.5 && !trackingFired.midpoint) {\n trackingFired.midpoint = true;\n fireTrackingPixels(currentAd.trackingUrls.midpoint);\n }\n if (progress >= 0.75 && !trackingFired.thirdQuartile) {\n trackingFired.thirdQuartile = true;\n fireTrackingPixels(currentAd.trackingUrls.thirdQuartile);\n }\n });\n adVideoElement.addEventListener(\"playing\", () => {\n if (!currentAd || trackingFired.start) return;\n trackingFired.start = true;\n fireTrackingPixels(currentAd.trackingUrls.start);\n console.log(\"[HlsAdPlayer] Ad started playing\");\n });\n adVideoElement.addEventListener(\"ended\", () => {\n if (!currentAd || trackingFired.complete) return;\n trackingFired.complete = true;\n fireTrackingPixels(currentAd.trackingUrls.complete);\n console.log(\"[HlsAdPlayer] Ad completed\");\n handleAdComplete();\n });\n adVideoElement.addEventListener(\"error\", (e) => {\n console.error(\"[HlsAdPlayer] Ad video error:\", e);\n if (currentAd) {\n fireTrackingPixels(currentAd.trackingUrls.error);\n }\n handleAdError();\n });\n adVideoElement.addEventListener(\"volumechange\", () => {\n if (!currentAd) return;\n if (adVideoElement.muted) {\n fireTrackingPixels(currentAd.trackingUrls.mute);\n } else {\n fireTrackingPixels(currentAd.trackingUrls.unmute);\n }\n });\n adVideoElement.addEventListener(\"pause\", () => {\n if (currentAd && !adVideoElement.ended) {\n fireTrackingPixels(currentAd.trackingUrls.pause);\n }\n });\n adVideoElement.addEventListener(\"play\", () => {\n if (currentAd && adVideoElement.currentTime > 0) {\n fireTrackingPixels(currentAd.trackingUrls.resume);\n }\n });\n }\n function setAdPlayingFlag(isPlaying) {\n if (isPlaying) {\n contentVideo.dataset.stormcloudAdPlaying = \"true\";\n } else {\n delete contentVideo.dataset.stormcloudAdPlaying;\n }\n }\n function handleAdComplete() {\n console.log(\"[HlsAdPlayer] Handling ad completion\");\n adPlaying = false;\n setAdPlayingFlag(false);\n contentVideo.muted = true;\n contentVideo.volume = 0;\n if (adContainerEl) {\n adContainerEl.style.display = \"none\";\n adContainerEl.style.pointerEvents = \"none\";\n }\n if (options?.continueLiveStreamDuringAds) {\n if (contentVideo.paused) {\n console.log(\"[HlsAdPlayer] Content video paused in live mode, resuming playback\");\n contentVideo.play().catch(() => {\n });\n } else {\n console.log(\"[HlsAdPlayer] Content video already playing in live mode\");\n }\n }\n emit(\"content_resume\");\n }\n function handleAdError() {\n console.log(\"[HlsAdPlayer] Handling ad error\");\n adPlaying = false;\n setAdPlayingFlag(false);\n contentVideo.muted = true;\n contentVideo.volume = 0;\n if (adContainerEl) {\n adContainerEl.style.display = \"none\";\n adContainerEl.style.pointerEvents = \"none\";\n }\n emit(\"ad_error\");\n }\n return {\n initialize() {\n console.log(\"[HlsAdPlayer] Initializing\");\n if (!adContainerEl) {\n const container = document.createElement(\"div\");\n container.style.position = \"absolute\";\n container.style.left = \"0\";\n container.style.top = \"0\";\n container.style.right = \"0\";\n container.style.bottom = \"0\";\n container.style.display = \"none\";\n container.style.alignItems = \"center\";\n container.style.justifyContent = \"center\";\n container.style.pointerEvents = \"none\";\n container.style.zIndex = \"30\";\n container.style.backgroundColor = \"#000\";\n contentVideo.parentElement?.appendChild(container);\n adContainerEl = container;\n }\n },\n async requestAds(vastTagUrl) {\n console.log(\"[HlsAdPlayer] Requesting ads:\", vastTagUrl);\n if (adPlaying) {\n console.warn(\n \"[HlsAdPlayer] Cannot request new ads while an ad is playing\"\n );\n return Promise.reject(new Error(\"Ad already playing\"));\n }\n try {\n sessionId = generateSessionId();\n let ad;\n if (preloadedAds.has(vastTagUrl)) {\n ad = preloadedAds.get(vastTagUrl);\n preloadedAds.delete(vastTagUrl);\n console.log(\n \"[HlsAdPlayer] Using preloaded VAST response:\",\n vastTagUrl\n );\n } else {\n ad = await fetchAndParseVastAd(vastTagUrl);\n }\n if (!ad) {\n console.warn(\"[HlsAdPlayer] No ads available from VAST response\");\n emit(\"ad_error\");\n return Promise.reject(new Error(\"No ads available from VAST response\"));\n }\n currentAd = ad;\n console.log(\n `[HlsAdPlayer] Ad parsed: ${ad.title}, duration: ${ad.duration}s`\n );\n fireTrackingPixels(ad.trackingUrls.impression);\n trackingFired.impression = true;\n return Promise.resolve();\n } catch (error) {\n console.error(\"[HlsAdPlayer] Error requesting ads:\", error);\n emit(\"ad_error\");\n return Promise.reject(error);\n }\n },\n async play() {\n if (!currentAd) {\n console.warn(\n \"[HlsAdPlayer] Cannot play: No ad loaded (no ads available)\"\n );\n return Promise.reject(new Error(\"No ad loaded\"));\n }\n console.log(\"[HlsAdPlayer] Starting ad playback\");\n try {\n if (!adVideoElement) {\n adVideoElement = createAdVideoElement();\n adContainerEl?.appendChild(adVideoElement);\n setupAdEventListeners();\n }\n trackingFired = {\n impression: trackingFired.impression,\n start: false,\n firstQuartile: false,\n midpoint: false,\n thirdQuartile: false,\n complete: false\n };\n const contentVolume = contentVideo.volume;\n originalVolume = Math.max(\n 0,\n Math.min(1, contentVolume || originalVolume)\n );\n if (!options?.continueLiveStreamDuringAds) {\n contentVideo.pause();\n console.log(\"[HlsAdPlayer] Content paused (VOD mode)\");\n } else {\n console.log(\"[HlsAdPlayer] Content continues (Live mode)\");\n }\n console.log(\"[HlsAdPlayer] FORCE MUTING main video\");\n contentVideo.muted = true;\n contentVideo.volume = 0;\n adPlaying = true;\n setAdPlayingFlag(true);\n if (adVideoElement) {\n const adVolume = originalMutedState ? 0 : originalVolume;\n adVideoElement.volume = Math.max(0, Math.min(1, adVolume));\n adVideoElement.muted = false;\n console.log(\n `[HlsAdPlayer] Set ad video volume to ${adVideoElement.volume}, muted: ${adVideoElement.muted}, originalMutedState: ${originalMutedState}, contentVolume: ${contentVolume}`\n );\n }\n if (adContainerEl) {\n adContainerEl.style.display = \"flex\";\n adContainerEl.style.pointerEvents = \"auto\";\n }\n emit(\"content_pause\");\n const mediaFile = selectBestMediaFile(currentAd.mediaFiles);\n if (!mediaFile) {\n throw new Error(\"No media file available for ad\");\n }\n const isHlsAd = isHlsMediaFile(mediaFile);\n console.log(\n `[HlsAdPlayer] Loading ${isHlsAd ? \"HLS\" : \"progressive\"} ad from: ${mediaFile.url}`\n );\n if (isHlsAd && import_hls.default.isSupported()) {\n if (adHls) {\n adHls.destroy();\n }\n adHls = new import_hls.default({\n enableWorker: true,\n lowLatencyMode: false\n });\n adHls.loadSource(mediaFile.url);\n adHls.attachMedia(adVideoElement);\n adHls.on(import_hls.default.Events.MANIFEST_PARSED, () => {\n console.log(\"[HlsAdPlayer] HLS manifest parsed, starting playback\");\n adVideoElement.play().catch((error) => {\n console.error(\"[HlsAdPlayer] Error starting ad playback:\", error);\n handleAdError();\n });\n });\n adHls.on(import_hls.default.Events.ERROR, (event, data) => {\n console.error(\"[HlsAdPlayer] HLS error:\", data);\n if (data.fatal) {\n handleAdError();\n }\n });\n } else if (isHlsAd && adVideoElement.canPlayType(\"application/vnd.apple.mpegurl\")) {\n adVideoElement.src = mediaFile.url;\n adVideoElement.play().catch((error) => {\n console.error(\"[HlsAdPlayer] Error starting ad playback:\", error);\n handleAdError();\n });\n } else if (!isHlsAd && isProgressiveMediaFile(mediaFile)) {\n if (adHls) {\n adHls.destroy();\n adHls = void 0;\n }\n adVideoElement.src = mediaFile.url;\n adVideoElement.load();\n adVideoElement.play().catch((error) => {\n console.error(\"[HlsAdPlayer] Error starting progressive ad playback:\", error);\n handleAdError();\n });\n } else {\n throw new Error(`Unsupported ad media file type: ${mediaFile.type}`);\n }\n return Promise.resolve();\n } catch (error) {\n console.error(\"[HlsAdPlayer] Error playing ad:\", error);\n handleAdError();\n return Promise.reject(error);\n }\n },\n pause() {\n if (!adPlaying || !adVideoElement) {\n return;\n }\n try {\n if (adVideoElement && !adVideoElement.paused) {\n adVideoElement.pause();\n }\n } catch (error) {\n console.warn(\"[HlsAdPlayer] Error pausing ad:\", error);\n }\n },\n resume() {\n if (!adPlaying || !adVideoElement) {\n return;\n }\n try {\n if (adVideoElement && adVideoElement.paused) {\n adVideoElement.play().catch(() => {\n });\n }\n } catch (error) {\n console.warn(\"[HlsAdPlayer] Error resuming ad:\", error);\n }\n },\n async stop() {\n console.log(\"[HlsAdPlayer] Stopping ad\");\n adPlaying = false;\n setAdPlayingFlag(false);\n const previousMutedState = contentVideo.muted;\n contentVideo.muted = originalMutedState;\n contentVideo.volume = originalMutedState ? 0 : originalVolume;\n console.log(\n `[HlsAdPlayer] Restored mute state on stop: ${previousMutedState} -> ${originalMutedState}`\n );\n if (adContainerEl) {\n adContainerEl.style.display = \"none\";\n adContainerEl.style.pointerEvents = \"none\";\n }\n contentVideo.style.visibility = \"visible\";\n contentVideo.style.opacity = \"1\";\n if (options?.continueLiveStreamDuringAds) {\n if (contentVideo.paused) {\n console.log(\"[HlsAdPlayer] Content video paused in live mode, resuming playback on stop\");\n contentVideo.play().catch(() => {\n });\n }\n }\n if (adHls) {\n adHls.destroy();\n adHls = void 0;\n }\n if (adVideoElement) {\n adVideoElement.pause();\n adVideoElement.src = \"\";\n }\n currentAd = void 0;\n },\n destroy() {\n console.log(\"[HlsAdPlayer] Destroying\");\n destroyed = true;\n for (const timeoutId of pendingTimeouts) {\n clearTimeout(timeoutId);\n }\n pendingTimeouts = [];\n adPlaying = false;\n setAdPlayingFlag(false);\n contentVideo.muted = originalMutedState;\n contentVideo.volume = originalMutedState ? 0 : originalVolume;\n if (adHls) {\n adHls.destroy();\n adHls = void 0;\n }\n if (adVideoElement) {\n adVideoElement.pause();\n adVideoElement.src = \"\";\n adVideoElement.remove();\n adVideoElement = void 0;\n }\n if (adContainerEl?.parentElement) {\n adContainerEl.parentElement.removeChild(adContainerEl);\n }\n adContainerEl = void 0;\n currentAd = void 0;\n listeners.clear();\n preloadedAds.clear();\n preloadingAds.clear();\n },\n isAdPlaying() {\n return adPlaying;\n },\n resize(width, height) {\n console.log(`[HlsAdPlayer] Resizing to ${width}x${height}`);\n if (adContainerEl) {\n adContainerEl.style.width = `${width}px`;\n adContainerEl.style.height = `${height}px`;\n }\n if (adVideoElement) {\n adVideoElement.style.width = `${width}px`;\n adVideoElement.style.height = `${height}px`;\n }\n },\n on(event, listener) {\n if (!listeners.has(event)) listeners.set(event, /* @__PURE__ */ new Set());\n listeners.get(event).add(listener);\n },\n off(event, listener) {\n listeners.get(event)?.delete(listener);\n },\n updateOriginalMutedState(muted, volume) {\n const nextVolume = typeof volume === \"number\" && !Number.isNaN(volume) ? Math.max(0, Math.min(1, volume)) : originalVolume;\n console.log(\n `[HlsAdPlayer] updateOriginalMutedState called: { muted: ${originalMutedState} -> ${muted}, volume: ${originalVolume} -> ${nextVolume} }`\n );\n originalMutedState = muted;\n originalVolume = nextVolume;\n },\n getOriginalMutedState() {\n return originalMutedState;\n },\n getOriginalVolume() {\n return originalVolume;\n },\n setAdVolume(volume) {\n if (adVideoElement && adPlaying) {\n adVideoElement.volume = Math.max(0, Math.min(1, volume));\n }\n },\n getAdVolume() {\n if (adVideoElement && adPlaying) {\n return adVideoElement.volume;\n }\n return 1;\n },\n showPlaceholder() {\n contentVideo.style.opacity = \"0\";\n contentVideo.style.visibility = \"hidden\";\n if (!adContainerEl) {\n const container = document.createElement(\"div\");\n container.style.position = \"absolute\";\n container.style.left = \"0\";\n container.style.top = \"0\";\n container.style.right = \"0\";\n container.style.bottom = \"0\";\n container.style.display = \"none\";\n container.style.alignItems = \"center\";\n container.style.justifyContent = \"center\";\n container.style.pointerEvents = \"none\";\n container.style.zIndex = \"10\";\n container.style.backgroundColor = \"#000\";\n contentVideo.parentElement?.appendChild(container);\n adContainerEl = container;\n }\n if (adContainerEl) {\n adContainerEl.style.display = \"flex\";\n adContainerEl.style.pointerEvents = \"auto\";\n }\n },\n hidePlaceholder() {\n if (adContainerEl) {\n adContainerEl.style.display = \"none\";\n adContainerEl.style.pointerEvents = \"none\";\n }\n if (!adPlaying) {\n contentVideo.style.visibility = \"visible\";\n contentVideo.style.opacity = \"1\";\n }\n }\n };\n}\n\n// src/sdk/pal.ts\nvar PAL_SDK_URL = \"https://imasdk.googleapis.com/pal/sdkloader/pal.js\";\nvar _nonceLoader;\nvar _palLoadPromise;\nfunction loadPalSdk() {\n if (typeof window !== \"undefined\" && window.goog?.pal) {\n return Promise.resolve();\n }\n if (_palLoadPromise) return _palLoadPromise;\n _palLoadPromise = new Promise((resolve, reject) => {\n const existing = document.querySelector(\n 'script[data-pal=\"true\"]'\n );\n if (existing) {\n if (window.goog?.pal) {\n resolve();\n return;\n }\n const timeout = setTimeout(\n () => reject(new Error(\"PAL SDK load timeout\")),\n 1e4\n );\n existing.addEventListener(\"load\", () => {\n clearTimeout(timeout);\n resolve();\n });\n existing.addEventListener(\"error\", () => {\n clearTimeout(timeout);\n reject(new Error(\"PAL SDK load failed\"));\n });\n return;\n }\n const script = document.createElement(\"script\");\n script.src = PAL_SDK_URL;\n script.async = true;\n script.setAttribute(\"data-pal\", \"true\");\n script.onload = () => resolve();\n script.onerror = () => reject(new Error(\"PAL SDK load failed\"));\n document.head.appendChild(script);\n });\n return _palLoadPromise;\n}\nfunction getOrCreateNonceLoader() {\n if (_nonceLoader) return _nonceLoader;\n const goog = window.goog;\n const consentSettings = new goog.pal.ConsentSettings();\n consentSettings.allowStorage = true;\n _nonceLoader = new goog.pal.NonceLoader(consentSettings);\n return _nonceLoader;\n}\nfunction createPalNonceManager() {\n let currentNonce = \"\";\n let currentNonceManager;\n return {\n async generateNonce(options = {}) {\n try {\n await loadPalSdk();\n const loader = getOrCreateNonceLoader();\n const goog = window.goog;\n const request = new goog.pal.NonceRequest();\n request.adWillAutoPlay = options.adWillAutoPlay ?? true;\n request.adWillPlayMuted = options.adWillPlayMuted ?? false;\n request.continuousPlayback = options.continuousPlayback ?? true;\n request.descriptionUrl = options.descriptionUrl || (typeof window !== \"undefined\" ? window.location.href : \"\");\n request.iconsSupported = true;\n request.playerType = \"StormcloudVideoPlayer\";\n request.playerVersion = \"1.0\";\n request.supportedApiFrameworks = \"2,7,9\";\n request.url = options.descriptionUrl || (typeof window !== \"undefined\" ? window.location.href : \"\");\n request.videoWidth = options.videoWidth || 640;\n request.videoHeight = options.videoHeight || 480;\n if (options.ppid) request.ppid = options.ppid;\n if (options.sessionId) request.sessionId = options.sessionId;\n const manager = await loader.loadNonceManager(request);\n currentNonceManager = manager;\n currentNonce = manager.getNonce();\n console.log(\"[PAL] Nonce generated successfully\");\n return currentNonce;\n } catch (error) {\n console.warn(\"[PAL] Failed to generate nonce:\", error);\n currentNonce = \"\";\n currentNonceManager = void 0;\n return \"\";\n }\n },\n getCurrentNonce() {\n return currentNonce;\n },\n injectNonce(vastTagUrl) {\n if (!currentNonce || !vastTagUrl) return vastTagUrl;\n try {\n const url = new URL(vastTagUrl);\n url.searchParams.delete(\"paln\");\n url.searchParams.set(\"givn\", currentNonce);\n return url.toString();\n } catch {\n let base = vastTagUrl.replace(/([?&])paln=[^&]*/g, \"\").replace(/[?&]$/, \"\");\n const sep = base.includes(\"?\") ? \"&\" : \"?\";\n return `${base}${sep}givn=${encodeURIComponent(currentNonce)}`;\n }\n },\n sendPlaybackStart() {\n try {\n currentNonceManager?.sendPlaybackStart();\n } catch {\n }\n },\n sendPlaybackEnd() {\n try {\n currentNonceManager?.sendPlaybackEnd();\n } catch {\n }\n },\n sendAdClick() {\n try {\n currentNonceManager?.sendAdClick();\n } catch {\n }\n },\n sendAdTouch(event) {\n try {\n currentNonceManager?.sendAdTouch(event);\n } catch {\n }\n },\n reset() {\n currentNonce = \"\";\n currentNonceManager = void 0;\n }\n };\n}\n\n// src/utils/tracking.ts\nvar cachedBrowserId = null;\nfunction getClientInfo() {\n const ua = navigator.userAgent;\n const platform = navigator.platform;\n const vendor = navigator.vendor || \"\";\n const maxTouchPoints = navigator.maxTouchPoints || 0;\n const memory = navigator.deviceMemory || null;\n const hardwareConcurrency = navigator.hardwareConcurrency || 1;\n const screenInfo = {\n width: screen?.width,\n height: screen?.height,\n availWidth: screen?.availWidth,\n availHeight: screen?.availHeight,\n orientation: screen?.orientation?.type || \"\",\n pixelDepth: screen?.pixelDepth\n };\n let deviceType = \"desktop\";\n let brand = \"Unknown\";\n let os = \"Unknown\";\n let model = \"\";\n let isSmartTV = false;\n let isAndroid = false;\n let isWebView = false;\n let isWebApp = false;\n if (ua.includes(\"Web0S\")) {\n brand = \"LG\";\n os = \"webOS\";\n isSmartTV = true;\n deviceType = \"tv\";\n const webosMatch = ua.match(/Web0S\\/([^\\s]+)/);\n model = webosMatch ? `webOS ${webosMatch[1]}` : \"webOS TV\";\n } else if (ua.includes(\"Tizen\")) {\n brand = \"Samsung\";\n os = \"Tizen\";\n isSmartTV = true;\n deviceType = \"tv\";\n const tizenMatch = ua.match(/Tizen\\/([^\\s]+)/);\n const tvMatch = ua.match(/(?:Smart-TV|SMART-TV|TV)/i) ? \"Smart TV\" : \"\";\n model = tizenMatch ? `Tizen ${tizenMatch[1]} ${tvMatch}`.trim() : \"Tizen TV\";\n } else if (ua.includes(\"Philips\")) {\n brand = \"Philips\";\n os = \"Saphi\";\n isSmartTV = true;\n deviceType = \"tv\";\n } else if (ua.includes(\"Sharp\") || ua.includes(\"AQUOS\")) {\n brand = \"Sharp\";\n os = \"Android TV\";\n isSmartTV = true;\n deviceType = \"tv\";\n } else if (ua.includes(\"Android\") && (ua.includes(\"Sony\") || vendor.includes(\"Sony\"))) {\n brand = \"Sony\";\n os = \"Android TV\";\n isSmartTV = true;\n deviceType = \"tv\";\n } else if (ua.includes(\"Android\") && (ua.includes(\"NetCast\") || ua.includes(\"LG\"))) {\n brand = \"LG\";\n os = \"Android TV\";\n isSmartTV = true;\n deviceType = \"tv\";\n } else if (ua.includes(\" Roku\") || ua.includes(\"Roku/\")) {\n brand = \"Roku\";\n os = \"Roku OS\";\n isSmartTV = true;\n deviceType = \"tv\";\n } else if (ua.includes(\"AppleTV\")) {\n brand = \"Apple\";\n os = \"tvOS\";\n isSmartTV = true;\n deviceType = \"tv\";\n }\n if (ua.includes(\"Android\")) {\n isAndroid = true;\n os = \"Android\";\n deviceType = /Mobile/.test(ua) ? \"mobile\" : \"tablet\";\n if (ua.includes(\"Android\") && (maxTouchPoints === 0 || ua.includes(\"Google TV\") || ua.includes(\"XiaoMi\"))) {\n deviceType = \"tv\";\n isSmartTV = true;\n brand = brand === \"Unknown\" ? \"Android TV\" : brand;\n }\n const androidModelMatch = ua.match(/\\(([^)]*Android[^)]*)\\)/);\n if (androidModelMatch && androidModelMatch[1]) {\n model = androidModelMatch[1];\n }\n }\n if (/iPad|iPhone|iPod/.test(ua)) {\n os = \"iOS\";\n deviceType = \"mobile\";\n brand = \"Apple\";\n if (navigator.maxTouchPoints > 1 && /iPad/.test(ua)) {\n deviceType = \"tablet\";\n }\n }\n if (!isAndroid && !isSmartTV && !/Mobile/.test(ua)) {\n if (ua.includes(\"Windows\")) {\n os = \"Windows\";\n deviceType = \"desktop\";\n } else if (ua.includes(\"Mac\") && !/iPhone/.test(ua)) {\n os = \"macOS\";\n deviceType = \"desktop\";\n if (maxTouchPoints > 1) deviceType = \"tablet\";\n } else if (ua.includes(\"Linux\")) {\n os = \"Linux\";\n deviceType = \"desktop\";\n }\n }\n if (brand === \"Unknown\") {\n if (vendor.includes(\"Google\") || ua.includes(\"Chrome\")) brand = \"Google\";\n if (vendor.includes(\"Apple\")) brand = \"Apple\";\n if (vendor.includes(\"Samsung\") || ua.includes(\"SM-\")) brand = \"Samsung\";\n }\n isWebView = /wv|WebView|Linux; U;/.test(ua);\n if (window?.outerHeight === 0 && window?.outerWidth === 0) {\n isWebView = true;\n }\n isWebApp = window.matchMedia(\"(display-mode: standalone)\").matches || window.navigator.standalone === true || window.screen?.orientation?.angle !== void 0;\n return {\n brand,\n os,\n model: model || ua.substring(0, 50) + \"...\",\n deviceType,\n isSmartTV,\n isAndroid,\n isWebView,\n isWebApp,\n domain: window.location.hostname,\n origin: window.location.origin,\n path: window.location.pathname,\n userAgent: ua,\n vendor,\n platform,\n screen: screenInfo,\n hardwareConcurrency,\n deviceMemory: memory,\n maxTouchPoints,\n language: navigator.language,\n languages: navigator.languages?.join(\",\") || \"\",\n cookieEnabled: navigator.cookieEnabled,\n doNotTrack: navigator.doNotTrack || \"\",\n referrer: document.referrer,\n visibilityState: document.visibilityState\n };\n}\nasync function getBrowserID(clientInfo) {\n if (cachedBrowserId) {\n return cachedBrowserId;\n }\n const fingerprintString = JSON.stringify(clientInfo);\n if (typeof crypto !== \"undefined\" && crypto.subtle && crypto.subtle.digest) {\n try {\n await crypto.subtle.digest(\"SHA-256\", new Uint8Array([1, 2, 3]));\n let encodedData;\n if (typeof TextEncoder !== \"undefined\") {\n encodedData = new TextEncoder().encode(fingerprintString);\n } else {\n const utf8 = unescape(encodeURIComponent(fingerprintString));\n const buffer = new Uint8Array(utf8.length);\n for (let i = 0; i < utf8.length; i++) {\n buffer[i] = utf8.charCodeAt(i);\n }\n encodedData = buffer;\n }\n const hashBuffer = await crypto.subtle.digest(\"SHA-256\", encodedData);\n const hashArray = Array.from(new Uint8Array(hashBuffer));\n const hashHex = hashArray.map((b) => b.toString(16).padStart(2, \"0\")).join(\"\");\n cachedBrowserId = hashHex;\n return hashHex;\n } catch (error) {\n console.warn(\n \"[StormcloudVideoPlayer] crypto.subtle.digest not supported, using fallback hash\"\n );\n }\n }\n let hash = 0;\n for (let i = 0; i < fingerprintString.length; i++) {\n const char = fingerprintString.charCodeAt(i);\n hash = (hash << 5) - hash + char;\n hash = hash & hash;\n }\n const fallbackHash = Math.abs(hash).toString(16).padStart(8, \"0\");\n const timestamp = Date.now().toString(16).padStart(12, \"0\");\n const random = Math.random().toString(16).substring(2, 14).padStart(12, \"0\");\n cachedBrowserId = (fallbackHash + timestamp + random).padEnd(64, \"0\");\n return cachedBrowserId;\n}\nvar PLAYER_TRACKING_BASE_URL = \"https://adstorm.co/api-adstorm-dev/adstorm/player-tracking\";\nvar TRACK_URL = `${PLAYER_TRACKING_BASE_URL}/metrics/ingest`;\nvar HEARTBEAT_URL = `${PLAYER_TRACKING_BASE_URL}/heartbeat`;\nvar IMPRESSIONS_URL = `${PLAYER_TRACKING_BASE_URL}/impressions/ingest`;\nfunction buildHeaders(licenseKey) {\n const headers = {\n \"Content-Type\": \"application/json\"\n };\n if (licenseKey) {\n headers[\"Authorization\"] = `Bearer ${licenseKey}`;\n }\n return headers;\n}\nasync function sendTrackRequest(licenseKey, body) {\n const response = await fetch(TRACK_URL, {\n method: \"POST\",\n headers: buildHeaders(licenseKey),\n body: JSON.stringify(body)\n });\n if (!response.ok) {\n throw new Error(`HTTP error! status: ${response.status}`);\n }\n await response.json();\n}\nasync function postJson(url, licenseKey, body) {\n const response = await fetch(url, {\n method: \"POST\",\n headers: buildHeaders(licenseKey),\n body: JSON.stringify(body)\n });\n if (!response.ok) {\n throw new Error(`HTTP error! status: ${response.status}`);\n }\n await response.json();\n}\nasync function buildPlayerMetricEvent(licenseKey, context = {}, flags = {}) {\n const clientInfo = getClientInfo();\n const browserId = await getBrowserID(clientInfo);\n const captureAt = flags.captureAt ?? (/* @__PURE__ */ new Date()).toISOString();\n return {\n player_id: browserId,\n browserId,\n device_type: clientInfo.deviceType,\n deviceType: clientInfo.deviceType,\n input_stream_type: context.inputStreamType,\n os: clientInfo.os,\n ad_loaded: flags.adLoaded,\n ad_detect: flags.adDetect,\n license_key: licenseKey,\n capture_at: captureAt,\n timestamp: captureAt\n };\n}\nasync function sendInitialTracking(licenseKey, context = {}) {\n try {\n const clientInfo = getClientInfo();\n const browserId = await getBrowserID(clientInfo);\n const trackingData = {\n browserId,\n ...clientInfo\n };\n await sendTrackRequest(licenseKey, {\n events: [\n {\n player_id: browserId,\n device_type: clientInfo.deviceType,\n input_stream_type: context.inputStreamType,\n os: clientInfo.os,\n ad_loaded: false,\n ad_detect: false,\n license_key: licenseKey,\n capture_at: (/* @__PURE__ */ new Date()).toISOString()\n }\n ],\n trackingData\n });\n } catch (error) {\n console.error(\n \"[StormcloudVideoPlayer] Error sending initial tracking data:\",\n error\n );\n }\n}\nasync function sendAdDetectTracking(licenseKey, adDetectInfo, context = {}) {\n try {\n await sendHeartbeat(licenseKey, context, {\n adDetect: true,\n captureAt: adDetectInfo.timestamp\n });\n } catch (error) {\n console.error(\n \"[StormcloudVideoPlayer] Error sending ad detect tracking:\",\n error\n );\n }\n}\nasync function sendAdLoadedTracking(licenseKey, adLoadedInfo, context = {}) {\n try {\n await sendHeartbeat(licenseKey, context, {\n adLoaded: true,\n captureAt: adLoadedInfo.timestamp\n });\n } catch (error) {\n console.error(\n \"[StormcloudVideoPlayer] Error sending ad loaded tracking:\",\n error\n );\n }\n}\nasync function sendAdImpressionTracking(licenseKey, adImpressionInfo, context = {}) {\n try {\n const metricEvent = await buildPlayerMetricEvent(licenseKey, context, {\n captureAt: adImpressionInfo.timestamp\n });\n await Promise.all([\n postJson(HEARTBEAT_URL, licenseKey, metricEvent),\n postJson(IMPRESSIONS_URL, licenseKey, {\n events: [\n {\n player_id: metricEvent.player_id,\n ad_played_count: 1,\n ad_url: adImpressionInfo.adUrl,\n license_key: licenseKey,\n capture_at: adImpressionInfo.timestamp\n }\n ]\n })\n ]);\n } catch (error) {\n console.error(\n \"[StormcloudVideoPlayer] Error sending ad impression tracking:\",\n error\n );\n }\n}\nasync function sendHeartbeat(licenseKey, context = {}, flags = {}) {\n try {\n const heartbeatData = await buildPlayerMetricEvent(\n licenseKey,\n context,\n flags\n );\n await postJson(HEARTBEAT_URL, licenseKey, heartbeatData);\n } catch (error) {\n console.error(\"[StormcloudVideoPlayer] Error sending heartbeat:\", error);\n }\n}\n\n// src/utils/polyfills.ts\nfunction polyfillURLSearchParams() {\n if (typeof URLSearchParams !== \"undefined\") {\n return;\n }\n class URLSearchParamsPolyfill {\n constructor(init) {\n this.params = /* @__PURE__ */ new Map();\n if (typeof init === \"string\") {\n this.parseQueryString(init);\n } else if (init instanceof URLSearchParamsPolyfill) {\n init.forEach((value, key) => {\n this.append(key, value);\n });\n }\n }\n parseQueryString(query) {\n const cleanQuery = query.startsWith(\"?\") ? query.slice(1) : query;\n if (!cleanQuery) return;\n cleanQuery.split(\"&\").forEach((param) => {\n const [key, value] = param.split(\"=\");\n if (key) {\n const decodedKey = this.safeDecodeURIComponent(key);\n const decodedValue = value ? this.safeDecodeURIComponent(value) : \"\";\n this.append(decodedKey, decodedValue);\n }\n });\n }\n safeDecodeURIComponent(str) {\n try {\n return decodeURIComponent(str.replace(/\\+/g, \" \"));\n } catch (e) {\n return str;\n }\n }\n append(name, value) {\n const values = this.params.get(name) || [];\n values.push(String(value));\n this.params.set(name, values);\n }\n delete(name) {\n this.params.delete(name);\n }\n get(name) {\n const values = this.params.get(name);\n return values && values.length > 0 && values[0] !== void 0 ? values[0] : null;\n }\n getAll(name) {\n return this.params.get(name) || [];\n }\n has(name) {\n return this.params.has(name);\n }\n set(name, value) {\n this.params.set(name, [String(value)]);\n }\n forEach(callback) {\n this.params.forEach((values, key) => {\n values.forEach((value) => {\n callback(value, key, this);\n });\n });\n }\n toString() {\n const parts = [];\n this.params.forEach((values, key) => {\n values.forEach((value) => {\n parts.push(`${encodeURIComponent(key)}=${encodeURIComponent(value)}`);\n });\n });\n return parts.join(\"&\");\n }\n }\n window.URLSearchParams = URLSearchParamsPolyfill;\n}\nfunction polyfillTextEncoder() {\n if (typeof TextEncoder !== \"undefined\") {\n return;\n }\n class TextEncoderPolyfill {\n constructor() {\n this.encoding = \"utf-8\";\n }\n encode(str) {\n const utf8 = [];\n for (let i = 0; i < str.length; i++) {\n let charcode = str.charCodeAt(i);\n if (charcode < 128) {\n utf8.push(charcode);\n } else if (charcode < 2048) {\n utf8.push(192 | charcode >> 6, 128 | charcode & 63);\n } else if (charcode < 55296 || charcode >= 57344) {\n utf8.push(\n 224 | charcode >> 12,\n 128 | charcode >> 6 & 63,\n 128 | charcode & 63\n );\n } else {\n i++;\n charcode = 65536 + ((charcode & 1023) << 10 | str.charCodeAt(i) & 1023);\n utf8.push(\n 240 | charcode >> 18,\n 128 | charcode >> 12 & 63,\n 128 | charcode >> 6 & 63,\n 128 | charcode & 63\n );\n }\n }\n return new Uint8Array(utf8);\n }\n }\n window.TextEncoder = TextEncoderPolyfill;\n}\nfunction polyfillPromiseFinally() {\n if (typeof Promise !== \"undefined\" && !Promise.prototype.finally) {\n Promise.prototype.finally = function(callback) {\n const constructor = this.constructor;\n return this.then(\n (value) => constructor.resolve(callback()).then(() => value),\n (reason) => constructor.resolve(callback()).then(() => {\n throw reason;\n })\n );\n };\n }\n}\nfunction polyfillObjectAssign() {\n if (typeof Object.assign !== \"function\") {\n Object.assign = function(target, ...sources) {\n if (target == null) {\n throw new TypeError(\"Cannot convert undefined or null to object\");\n }\n const to = Object(target);\n for (let i = 0; i < sources.length; i++) {\n const nextSource = sources[i];\n if (nextSource != null) {\n for (const nextKey in nextSource) {\n if (Object.prototype.hasOwnProperty.call(nextSource, nextKey)) {\n to[nextKey] = nextSource[nextKey];\n }\n }\n }\n }\n return to;\n };\n }\n}\nfunction polyfillArrayFrom() {\n if (!Array.from) {\n Array.from = function(arrayLike, mapFn, thisArg) {\n const items = Object(arrayLike);\n if (arrayLike == null) {\n throw new TypeError(\"Array.from requires an array-like object\");\n }\n const len = items.length >>> 0;\n const result = new Array(len);\n for (let i = 0; i < len; i++) {\n if (mapFn) {\n result[i] = mapFn.call(thisArg, items[i], i);\n } else {\n result[i] = items[i];\n }\n }\n return result;\n };\n }\n}\nfunction polyfillStringStartsWith() {\n if (!String.prototype.startsWith) {\n String.prototype.startsWith = function(search, pos) {\n pos = !pos || pos < 0 ? 0 : +pos;\n return this.substring(pos, pos + search.length) === search;\n };\n }\n}\nfunction polyfillStringEndsWith() {\n if (!String.prototype.endsWith) {\n String.prototype.endsWith = function(search, length) {\n if (length === void 0 || length > this.length) {\n length = this.length;\n }\n return this.substring(length - search.length, length) === search;\n };\n }\n}\nfunction polyfillStringIncludes() {\n if (!String.prototype.includes) {\n String.prototype.includes = function(search, start) {\n if (typeof start !== \"number\") {\n start = 0;\n }\n if (start + search.length > this.length) {\n return false;\n }\n return this.indexOf(search, start) !== -1;\n };\n }\n}\nfunction initializePolyfills() {\n polyfillObjectAssign();\n polyfillArrayFrom();\n polyfillStringStartsWith();\n polyfillStringEndsWith();\n polyfillStringIncludes();\n polyfillURLSearchParams();\n polyfillTextEncoder();\n polyfillPromiseFinally();\n}\n\n// src/utils/browserCompat.ts\nfunction getChromeVersion(ua) {\n const match = ua.match(/Chrome\\/(\\d+)/);\n return match && match[1] ? parseInt(match[1], 10) : 0;\n}\nfunction getWebKitVersion(ua) {\n const match = ua.match(/AppleWebKit\\/(\\d+)/);\n return match && match[1] ? parseInt(match[1], 10) : 0;\n}\nfunction getPlatform() {\n if (\"userAgentData\" in navigator && navigator.userAgentData?.platform) {\n return navigator.userAgentData.platform;\n }\n const ua = navigator.userAgent;\n if (/Mac|iPhone|iPad|iPod/i.test(ua)) {\n return /iPhone|iPad|iPod/i.test(ua) ? \"iPhone\" : \"MacIntel\";\n }\n if (/Win/i.test(ua)) {\n return \"Win32\";\n }\n if (/Linux/i.test(ua)) {\n return /Android/i.test(ua) ? \"Linux armv8l\" : \"Linux x86_64\";\n }\n if (/CrOS/i.test(ua)) {\n return \"CrOS\";\n }\n return navigator.platform || \"Unknown\";\n}\nfunction detectBrowser() {\n const ua = navigator.userAgent;\n const platform = getPlatform();\n let name = \"Unknown\";\n let version = \"0\";\n let majorVersion = 0;\n let isSmartTV = false;\n let isLegacyTV = false;\n let supportsModernJS = true;\n let webOSVersion;\n let tizenVersion;\n let chromeVersionNum;\n const chromeVersion = getChromeVersion(ua);\n const webkitVersion = getWebKitVersion(ua);\n chromeVersionNum = chromeVersion > 0 ? chromeVersion : void 0;\n if (/Web0S|webOS|LG Browser|LGSTB/i.test(ua)) {\n name = \"LG WebOS\";\n isSmartTV = true;\n let match = ua.match(/Web0S[/\\s]*([\\d.]+)/i) || ua.match(/webOS[/\\s]*([\\d.]+)/i);\n if (!match || !match[1]) {\n match = ua.match(/webOSTV[/\\s-]*([\\d.]+)/i) || ua.match(/webOS\\.TV[/\\s-]*([\\d.]+)/i);\n }\n if (match && match[1]) {\n version = match[1];\n const parts = version.split(\".\");\n majorVersion = parts[0] ? parseInt(parts[0], 10) : 0;\n webOSVersion = majorVersion;\n } else if (chromeVersion > 0) {\n if (chromeVersion >= 79) {\n webOSVersion = 6;\n version = \"6.0\";\n majorVersion = 6;\n } else if (chromeVersion >= 68) {\n webOSVersion = 5;\n version = \"5.0\";\n majorVersion = 5;\n } else if (chromeVersion >= 53) {\n webOSVersion = 4;\n version = \"4.0\";\n majorVersion = 4;\n } else if (chromeVersion >= 38) {\n webOSVersion = 3;\n version = \"3.0\";\n majorVersion = 3;\n } else {\n webOSVersion = 2;\n version = \"2.0\";\n majorVersion = 2;\n }\n } else {\n version = \"Unknown\";\n webOSVersion = void 0;\n }\n isLegacyTV = webOSVersion !== void 0 && webOSVersion < 3;\n } else if (/Tizen/i.test(ua)) {\n name = \"Samsung Tizen\";\n isSmartTV = true;\n const match = ua.match(/Tizen[/\\s]*([\\d.]+)/i);\n version = match && match[1] ? match[1] : \"Unknown\";\n if (version !== \"Unknown\") {\n const parts = version.split(\".\");\n majorVersion = parts[0] ? parseInt(parts[0], 10) : 0;\n tizenVersion = majorVersion;\n }\n isLegacyTV = tizenVersion !== void 0 && tizenVersion < 3;\n } else if (/SMART-TV|SmartTV/i.test(ua)) {\n name = \"Smart TV\";\n isSmartTV = true;\n isLegacyTV = chromeVersion > 0 && chromeVersion < 53;\n } else if (/NetCast/i.test(ua)) {\n name = \"LG NetCast\";\n isSmartTV = true;\n isLegacyTV = true;\n } else if (/BRAVIA/i.test(ua)) {\n name = \"Sony BRAVIA\";\n isSmartTV = true;\n isLegacyTV = chromeVersion > 0 && chromeVersion < 53;\n } else {\n if (chromeVersion > 0) {\n name = \"Chrome\";\n version = chromeVersion.toString();\n majorVersion = chromeVersion;\n if (chromeVersion < 50) {\n supportsModernJS = false;\n }\n }\n if (webkitVersion > 0 && webkitVersion < 600) {\n supportsModernJS = false;\n }\n }\n if (typeof Promise === \"undefined\" || typeof Map === \"undefined\" || typeof Set === \"undefined\") {\n supportsModernJS = false;\n }\n if (typeof URLSearchParams === \"undefined\") {\n supportsModernJS = false;\n }\n return {\n name,\n version,\n majorVersion,\n isSmartTV,\n isLegacyTV,\n platform,\n supportsModernJS,\n webOSVersion,\n tizenVersion,\n chromeVersion: chromeVersionNum\n };\n}\nfunction getBrowserConfigOverrides() {\n const browser = detectBrowser();\n const overrides = {};\n if (browser.isSmartTV) {\n overrides.allowNativeHls = true;\n }\n return overrides;\n}\nfunction logBrowserInfo(debug = false) {\n if (!debug) return;\n const browser = detectBrowser();\n console.log(\"[StormcloudVideoPlayer] Browser Compatibility Info:\", {\n browser: `${browser.name} ${browser.version}`,\n platform: browser.platform,\n isSmartTV: browser.isSmartTV,\n isLegacyTV: browser.isLegacyTV,\n supportsModernJS: browser.supportsModernJS,\n ...browser.webOSVersion !== void 0 ? { webOSVersion: browser.webOSVersion } : {},\n ...browser.tizenVersion !== void 0 ? { tizenVersion: browser.tizenVersion } : {},\n ...browser.chromeVersion !== void 0 ? { chromeVersion: browser.chromeVersion } : {},\n userAgent: navigator.userAgent\n });\n}\n\n// src/player/StormcloudVideoPlayer.ts\nvar StormcloudVideoPlayer = class {\n constructor(config) {\n this.attached = false;\n this.inAdBreak = false;\n this.ptsDriftEmaMs = 0;\n this.adPodQueue = [];\n this.vmapBreaks = [];\n this.consumedVmapBreakIds = /* @__PURE__ */ new Set();\n this.lastHeartbeatTime = 0;\n this.currentAdIndex = 0;\n this.totalAdsInBreak = 0;\n this.showAds = false;\n this.isLiveStream = false;\n this.nativeHlsMode = false;\n this.videoSrcProtection = null;\n this.bufferedSegmentsCount = 0;\n this.shouldAutoplayAfterBuffering = false;\n this.hasInitialBufferCompleted = false;\n this.adRequestTokenCounter = 0;\n this.activeAdRequestToken = null;\n this.adRequestWatchdogToken = null;\n this.adFailsafeToken = null;\n this.failedVastUrls = /* @__PURE__ */ new Set();\n this.temporaryFailureUrls = /* @__PURE__ */ new Map();\n this.temporaryFailureCooldownMs = 3e4;\n this.continuousFetchingActive = false;\n this.adRequestQueue = [];\n this.maxPlaceholderDurationMs = 5e3;\n this.isShowingPlaceholder = false;\n this.tsScte35Pids = /* @__PURE__ */ new Set();\n this.pmtPids = /* @__PURE__ */ new Set();\n this.processedTsScte35Sections = /* @__PURE__ */ new Set();\n this.pendingScte35Cues = /* @__PURE__ */ new Map();\n this.recentScte35CueKeys = /* @__PURE__ */ new Map();\n this.recentScte35CueLimit = 200;\n this.totalAdRequestsInBreak = 0;\n this.maxTotalAdRequestsPerBreak = 10;\n this.pendingAdBreak = null;\n this.consecutiveFailures = 0;\n this.maxConsecutiveFailures = 5;\n this.lastAdRequestTime = 0;\n this.minAdRequestIntervalMs = 3e3;\n this.backoffBaseMs = 1e3;\n this.maxBackoffMs = 15e3;\n this.globalConsecutiveNoFills = 0;\n this.globalNoFillThreshold = 3;\n this.globalNoFillCooldownUntil = 0;\n this.globalNoFillBackoffBaseMs = 5e3;\n this.globalNoFillBackoffMaxMs = 6e4;\n this.globalLastGamRequestTime = 0;\n this.globalMinGamIntervalMs = 3e3;\n this.preloadPool = [];\n this.maxPreloadPoolSize = 2;\n this.preloadPoolActive = false;\n this.preloadPoolLoopRunning = false;\n this.adDetectSentForCurrentBreak = false;\n this.palPlaybackStarted = false;\n this.continuousFetchLoopRunning = false;\n initializePolyfills();\n const browserOverrides = getBrowserConfigOverrides();\n this.config = { ...browserOverrides, ...config };\n this.video = config.videoElement;\n logBrowserInfo(config.debugAdTiming);\n this.adPlayer = this.createAdPlayer(false);\n this.palNonce = createPalNonceManager();\n }\n createAdPlayer(continueLiveStreamDuringAds) {\n if (this.config.debugAdTiming) {\n console.log(\"[StormcloudVideoPlayer] Creating HLS ad player\");\n }\n return createHlsAdPlayer(this.video, {\n continueLiveStreamDuringAds,\n ...this.config.licenseKey ? { licenseKey: this.config.licenseKey } : {},\n ...this.hls ? { mainHlsInstance: this.hls } : {}\n });\n }\n async load() {\n if (!this.attached) {\n this.attach();\n }\n try {\n await this.fetchAdConfiguration();\n } catch (error) {\n if (this.config.debugAdTiming) {\n console.warn(\n \"[StormcloudVideoPlayer] Failed to fetch ad configuration:\",\n error\n );\n }\n }\n this.palNonce.generateNonce({\n videoWidth: this.video.offsetWidth || this.video.clientWidth || 640,\n videoHeight: this.video.offsetHeight || this.video.clientHeight || 480,\n adWillAutoPlay: !!this.config.autoplay,\n adWillPlayMuted: !!this.config.muted,\n continuousPlayback: this.config.lowLatencyMode ?? false\n }).catch(() => {\n });\n this.initializeTracking();\n if (this.shouldUseNativeHls()) {\n this.nativeHlsMode = true;\n this.videoSrcProtection = this.config.src;\n this.video.src = this.config.src;\n this.isLiveStream = this.config.lowLatencyMode ?? false;\n if (this.config.debugAdTiming) {\n console.log(\n \"[StormcloudVideoPlayer] Using native HLS playback - VOD mode:\",\n {\n isLive: this.isLiveStream,\n allowNativeHls: this.config.allowNativeHls,\n adBehavior: \"vod (main video pauses during ads)\"\n }\n );\n }\n this.adPlayer.destroy();\n this.adPlayer = this.createAdPlayer(false);\n this.adPlayer.initialize();\n if (this.config.autoplay) {\n await this.video.play()?.catch(() => {\n });\n }\n return;\n }\n this.hls = new import_hls2.default({\n enableWorker: true,\n backBufferLength: 30,\n liveDurationInfinity: true,\n lowLatencyMode: !!this.config.lowLatencyMode,\n maxLiveSyncPlaybackRate: this.config.lowLatencyMode ? 1.5 : 1,\n ...this.config.lowLatencyMode ? { liveSyncDuration: 2 } : {},\n maxBufferLength: 30,\n maxMaxBufferLength: 600,\n maxBufferSize: 60 * 1e3 * 1e3,\n maxBufferHole: 0.5,\n highBufferWatchdogPeriod: 2,\n nudgeOffset: 0.1,\n nudgeMaxRetry: 3,\n startPosition: -1\n });\n this.hls.on(import_hls2.default.Events.MEDIA_ATTACHED, () => {\n this.hls?.loadSource(this.config.src);\n });\n this.hls.on(import_hls2.default.Events.MANIFEST_PARSED, async (_, data) => {\n if (this.config.allowNativeHls === false) {\n this.isLiveStream = true;\n } else {\n this.isLiveStream = this.hls?.levels?.some(\n (level) => level?.details?.live === true || level?.details?.type === \"LIVE\"\n ) ?? false;\n }\n if (this.config.debugAdTiming) {\n const adBehavior = this.shouldContinueLiveStreamDuringAds() ? \"live (main video continues muted during ads)\" : \"vod (main video pauses during ads)\";\n console.log(\"[StormcloudVideoPlayer] Stream type detected:\", {\n isLive: this.isLiveStream,\n allowNativeHls: this.config.allowNativeHls,\n adBehavior\n });\n }\n this.adPlayer.destroy();\n this.adPlayer = this.createAdPlayer(this.shouldContinueLiveStreamDuringAds());\n this.adPlayer.initialize();\n this.bufferedSegmentsCount = 0;\n this.hasInitialBufferCompleted = false;\n this.shouldAutoplayAfterBuffering = !!this.config.autoplay;\n const minSegments = this.config.minSegmentsBeforePlay ?? 2;\n if (this.config.debugAdTiming) {\n console.log(\n \"[StormcloudVideoPlayer] Waiting for\",\n minSegments,\n \"segments to buffer before playback\"\n );\n }\n if (minSegments === 0 || !this.config.autoplay) {\n this.hasInitialBufferCompleted = true;\n if (this.config.autoplay) {\n await this.video.play()?.catch(() => {\n });\n }\n }\n });\n this.hls.on(import_hls2.default.Events.LEVEL_LOADED, (_evt, data) => {\n if (this.inAdBreak || this.pendingAdBreak) {\n return;\n }\n const details = data?.details;\n if (!details || !details.fragments || details.fragments.length === 0) {\n return;\n }\n const fragmentsToScan = Math.min(5, details.fragments.length);\n for (let i = 0; i < fragmentsToScan; i++) {\n const frag = details.fragments[i];\n const tagList = frag?.tagList;\n if (!Array.isArray(tagList)) continue;\n for (const entry of tagList) {\n let tag = \"\";\n let value = \"\";\n if (Array.isArray(entry)) {\n tag = String(entry[0] ?? \"\");\n value = String(entry[1] ?? \"\");\n } else if (typeof entry === \"string\") {\n const idx = entry.indexOf(\":\");\n if (idx >= 0) {\n tag = entry.substring(0, idx);\n value = entry.substring(idx + 1);\n } else {\n tag = entry;\n }\n }\n if (!tag) continue;\n if (tag.includes(\"EXT-X-CUE-OUT\") || tag.includes(\"EXT-X-DATERANGE\")) {\n const attrs = tag.includes(\"EXT-X-DATERANGE\") ? this.parseAttributeList(value) : {};\n const hasScteOut = tag.includes(\"EXT-X-CUE-OUT\") || \"SCTE35-OUT\" in attrs || attrs[\"SCTE35-OUT\"] !== void 0;\n if (hasScteOut) {\n const durationSeconds = this.parseCueOutDuration(value);\n const marker = {\n type: \"start\",\n ...durationSeconds !== void 0 ? { durationSeconds } : {},\n raw: { tag, value, earlyDetection: true }\n };\n if (this.config.debugAdTiming) {\n console.log(\"[StormcloudVideoPlayer] \\u{1F3AF} EARLY SCTE-35 DETECTION: Ad break marker found in fragment\", i, \"- starting pre-fetch (NOT playing yet)\");\n }\n this.onScte35Cue(marker, {\n ...this.createScte35CueContext(\"manifest\", \"early\", frag)\n });\n return;\n }\n }\n }\n }\n });\n this.hls.on(import_hls2.default.Events.FRAG_BUFFERED, async (_evt, data) => {\n if (this.hasInitialBufferCompleted) {\n return;\n }\n this.bufferedSegmentsCount++;\n const minSegments = this.config.minSegmentsBeforePlay ?? 2;\n if (this.config.debugAdTiming) {\n console.log(\n `[StormcloudVideoPlayer] Buffered segment ${this.bufferedSegmentsCount}/${minSegments}`\n );\n }\n if (this.bufferedSegmentsCount >= minSegments) {\n this.hasInitialBufferCompleted = true;\n if (this.shouldAutoplayAfterBuffering) {\n if (this.config.debugAdTiming) {\n console.log(\n `[StormcloudVideoPlayer] Initial buffer complete (${this.bufferedSegmentsCount} segments). Starting playback.`\n );\n }\n await this.video.play()?.catch((err) => {\n if (this.config.debugAdTiming) {\n console.warn(\"[StormcloudVideoPlayer] Autoplay failed:\", err);\n }\n });\n }\n }\n });\n this.hls.on(import_hls2.default.Events.FRAG_PARSING_METADATA, (_evt, data) => {\n const id3Tags = (data?.samples || []).map((s) => ({\n key: \"ID3\",\n value: s?.data,\n ptsSeconds: s?.pts\n }));\n id3Tags.forEach((tag) => this.onId3Tag(tag));\n });\n this.hls.on(import_hls2.default.Events.FRAG_LOADED, (_evt, data) => {\n this.processFragmentScte35Payload(\n data?.payload,\n typeof data?.frag?.sn === \"number\" ? data.frag.sn : void 0,\n this.getFragmentStartSeconds(data?.frag)\n );\n });\n this.hls.on(import_hls2.default.Events.FRAG_DECRYPTED, (_evt, data) => {\n this.processFragmentScte35Payload(\n data?.payload,\n typeof data?.frag?.sn === \"number\" ? data.frag.sn : void 0,\n this.getFragmentStartSeconds(data?.frag)\n );\n });\n this.hls.on(import_hls2.default.Events.FRAG_CHANGED, (_evt, data) => {\n const frag = data?.frag;\n const tagList = frag?.tagList;\n if (!Array.isArray(tagList)) {\n this.activatePendingScte35CuesForFragment(frag);\n return;\n }\n for (const entry of tagList) {\n let tag = \"\";\n let value = \"\";\n if (Array.isArray(entry)) {\n tag = String(entry[0] ?? \"\");\n value = String(entry[1] ?? \"\");\n } else if (typeof entry === \"string\") {\n const idx = entry.indexOf(\":\");\n if (idx >= 0) {\n tag = entry.substring(0, idx);\n value = entry.substring(idx + 1);\n } else {\n tag = entry;\n value = \"\";\n }\n }\n if (!tag) continue;\n if (tag.includes(\"EXT-X-CUE-OUT-CONT\")) {\n const prog = this.parseCueOutCont(value);\n const marker = {\n type: \"progress\",\n ...prog?.duration !== void 0 ? { durationSeconds: prog.duration } : {},\n ...prog?.elapsed !== void 0 ? { ptsSeconds: prog.elapsed } : {},\n raw: { tag, value }\n };\n this.onScte35Cue(marker, {\n ...this.createScte35CueContext(\"manifest\", \"playback\", frag)\n });\n } else if (tag.includes(\"EXT-X-CUE-OUT\")) {\n const durationSeconds = this.parseCueOutDuration(value);\n const marker = {\n type: \"start\",\n ...durationSeconds !== void 0 ? { durationSeconds } : {},\n raw: { tag, value }\n };\n this.onScte35Cue(marker, {\n ...this.createScte35CueContext(\"manifest\", \"playback\", frag)\n });\n } else if (tag.includes(\"EXT-X-CUE-IN\")) {\n this.onScte35Cue(\n { type: \"end\", raw: { tag, value } },\n {\n ...this.createScte35CueContext(\"manifest\", \"playback\", frag)\n }\n );\n } else if (tag.includes(\"EXT-X-DATERANGE\")) {\n const attrs = this.parseAttributeList(value);\n const hasScteOut = \"SCTE35-OUT\" in attrs || attrs[\"SCTE35-OUT\"] !== void 0;\n const hasScteIn = \"SCTE35-IN\" in attrs || attrs[\"SCTE35-IN\"] !== void 0;\n const klass = String(attrs[\"CLASS\"] ?? \"\");\n const duration = this.toNumber(attrs[\"DURATION\"]);\n if (hasScteOut || /com\\.apple\\.hls\\.cue/i.test(klass)) {\n const marker = {\n type: \"start\",\n ...duration !== void 0 ? { durationSeconds: duration } : {},\n raw: { tag, value, attrs }\n };\n this.onScte35Cue(marker, {\n ...this.createScte35CueContext(\"manifest\", \"playback\", frag)\n });\n }\n if (hasScteIn) {\n this.onScte35Cue(\n { type: \"end\", raw: { tag, value, attrs } },\n {\n ...this.createScte35CueContext(\"manifest\", \"playback\", frag)\n }\n );\n }\n }\n }\n this.activatePendingScte35CuesForFragment(frag);\n });\n this.hls.on(import_hls2.default.Events.ERROR, (_evt, data) => {\n if (data?.fatal) {\n switch (data.type) {\n case import_hls2.default.ErrorTypes.NETWORK_ERROR:\n this.hls?.startLoad();\n break;\n case import_hls2.default.ErrorTypes.MEDIA_ERROR:\n this.hls?.recoverMediaError();\n break;\n default:\n this.destroy();\n break;\n }\n }\n });\n this.hls.attachMedia(this.video);\n }\n attachImaEventListeners() {\n this.adPlayer.on(\"all_ads_completed\", () => {\n sendAdImpressionTracking(\n this.config.licenseKey,\n { source: \"hls\", adIndex: this.currentAdIndex, timestamp: (/* @__PURE__ */ new Date()).toISOString() }\n ).catch(() => {\n });\n const remaining = this.getRemainingAdMs();\n this.consecutiveFailures = 0;\n if (this.config.debugAdTiming) {\n console.log(\n `[StormcloudVideoPlayer] all_ads_completed event received - remaining=${remaining}ms, queued ads=${this.adRequestQueue.length}`,\n this.adRequestQueue.length > 0 ? { queuedUrls: [...this.adRequestQueue] } : {}\n );\n }\n if (this.inAdBreak) {\n if (remaining > 500) {\n this.tryNextAvailableAdWithRateLimit();\n } else {\n this.handleAdPodComplete();\n }\n }\n });\n this.adPlayer.on(\"ad_error\", (errorPayload) => {\n let errorMessage = \"Ad playback failed\";\n if (errorPayload) {\n const errorCode = errorPayload.code || errorPayload.errorCode || \"unknown\";\n const vastErrorCode = errorPayload.vastErrorCode;\n const message = errorPayload.message || errorPayload.errorMessage || \"Unknown error\";\n const cause = errorPayload.cause || errorPayload.innerError || errorPayload.error;\n errorMessage = `Ad error: AdError ${errorCode}: ${message}`;\n if (vastErrorCode && vastErrorCode !== \"N/A\" && vastErrorCode !== errorCode) {\n errorMessage += ` (VAST Error Code: ${vastErrorCode})`;\n }\n if (cause) {\n const causeMessage = typeof cause === \"string\" ? cause : cause.message || String(cause);\n errorMessage += `. Caused by: ${causeMessage}`;\n }\n }\n console.error(\"[AD-ERROR]\", errorMessage, errorPayload || \"\");\n this.handleAdFailure();\n });\n this.adPlayer.on(\"content_pause\", () => {\n this.clearAdFailsafeTimer();\n this.clearAdRequestWatchdog();\n this.activeAdRequestToken = null;\n this.showAds = true;\n this.resetGamNoFillCounter();\n if (this.inAdBreak && this.expectedAdBreakDurationMs != null && this.adStopTimerId == null) {\n this.scheduleAdStopCountdown(this.getRemainingAdMs());\n if (this.config.debugAdTiming) {\n console.log(\"[StormcloudVideoPlayer] Starting ad break timer on content_pause (first ad starting)\");\n }\n }\n const currentMuted = this.video.muted;\n const currentVolume = this.video.volume;\n const adVolume = currentMuted ? 0 : currentVolume;\n this.adPlayer.setAdVolume(adVolume);\n if (this.isShowingPlaceholder) {\n if (this.config.debugAdTiming) {\n console.log(\"[StormcloudVideoPlayer] Hiding placeholder - new ads starting\");\n }\n this.adPlayer.hidePlaceholder();\n this.isShowingPlaceholder = false;\n }\n });\n this.adPlayer.on(\"content_resume\", () => {\n sendAdImpressionTracking(\n this.config.licenseKey,\n { source: \"hls\", adIndex: this.currentAdIndex, timestamp: (/* @__PURE__ */ new Date()).toISOString() }\n ).catch(() => {\n });\n if (!this.video.muted) {\n this.video.muted = true;\n this.video.volume = 0;\n if (this.config.debugAdTiming) {\n console.log(\"[StormcloudVideoPlayer] Muted video on content_resume (ad ended, gap between ads)\");\n }\n }\n this.clearAdFailsafeTimer();\n this.clearAdRequestWatchdog();\n this.activeAdRequestToken = null;\n this.showAds = false;\n if (!this.inAdBreak) {\n return;\n }\n this.consecutiveFailures = 0;\n const remaining = this.getRemainingAdMs();\n if (this.config.debugAdTiming) {\n console.log(\n `[CONTINUOUS-FETCH] content_resume event: remaining=${remaining}ms, queued ads=${this.adRequestQueue.length}`,\n this.adRequestQueue.length > 0 ? { queuedUrls: [...this.adRequestQueue] } : {}\n );\n }\n if (remaining > 500) {\n this.tryNextAvailableAdWithRateLimit();\n } else {\n this.handleAdPodComplete();\n }\n });\n }\n recreateAdController() {\n if (this.config.debugAdTiming) {\n console.log(\"[StormcloudVideoPlayer] Recreating AdController for new ad\");\n }\n const shouldShowPlaceholder = this.inAdBreak && this.showAds;\n if (shouldShowPlaceholder && this.adPlayer) {\n if (this.config.debugAdTiming) {\n console.log(\"[StormcloudVideoPlayer] Showing placeholder before destroying old AdController\");\n }\n this.showPlaceholderLayer();\n this.adPlayer.showPlaceholder();\n this.isShowingPlaceholder = true;\n }\n const preservedMutedState = this.adPlayer.getOriginalMutedState();\n const preservedVolumeState = this.adPlayer.getOriginalVolume();\n if (this.adPlayer) {\n try {\n this.adPlayer.destroy();\n this.video.muted = true;\n this.video.volume = 0;\n } catch (error) {\n if (this.config.debugAdTiming) {\n console.warn(\"[StormcloudVideoPlayer] Error destroying old AdController:\", error);\n }\n }\n }\n const continueLiveStreamDuringAds = this.shouldContinueLiveStreamDuringAds();\n this.adPlayer = this.createAdPlayer(continueLiveStreamDuringAds);\n this.adPlayer.initialize();\n this.adPlayer.updateOriginalMutedState(preservedMutedState, preservedVolumeState);\n this.attachImaEventListeners();\n if (shouldShowPlaceholder) {\n this.showPlaceholderLayer();\n this.adPlayer.showPlaceholder();\n this.isShowingPlaceholder = true;\n }\n }\n ensurePlaceholderContainer() {\n if (this.placeholderContainer) {\n return;\n }\n const container = document.createElement(\"div\");\n container.style.position = \"absolute\";\n container.style.left = \"0\";\n container.style.top = \"0\";\n container.style.right = \"0\";\n container.style.bottom = \"0\";\n container.style.display = \"none\";\n container.style.alignItems = \"center\";\n container.style.justifyContent = \"center\";\n container.style.pointerEvents = \"none\";\n container.style.zIndex = \"5\";\n container.style.backgroundColor = \"#000\";\n container.style.transition = \"opacity 0.3s ease-in-out\";\n container.style.opacity = \"0\";\n if (!this.video.parentElement) {\n if (this.config.debugAdTiming) {\n console.warn(\"[StormcloudVideoPlayer] Video element has no parent for placeholder container\");\n }\n return;\n }\n this.video.parentElement.appendChild(container);\n this.placeholderContainer = container;\n }\n showPlaceholderLayer() {\n this.ensurePlaceholderContainer();\n if (!this.placeholderContainer) {\n return;\n }\n if (!this.video.muted) {\n this.video.muted = true;\n this.video.volume = 0;\n if (this.config.debugAdTiming) {\n console.log(\"[StormcloudVideoPlayer] Muted video when showing placeholder\");\n }\n }\n const wasHidden = this.placeholderContainer.style.display === \"none\" || this.placeholderContainer.style.opacity === \"0\";\n if (wasHidden) {\n this.placeholderContainer.style.transition = \"none\";\n } else {\n this.placeholderContainer.style.transition = \"opacity 0.3s ease-in-out\";\n }\n this.placeholderContainer.style.backgroundColor = \"#000\";\n this.placeholderContainer.style.display = \"flex\";\n this.placeholderContainer.offsetHeight;\n this.placeholderContainer.style.opacity = \"1\";\n this.placeholderContainer.style.pointerEvents = \"auto\";\n if (wasHidden) {\n requestAnimationFrame(() => {\n if (this.placeholderContainer) {\n this.placeholderContainer.style.transition = \"opacity 0.3s ease-in-out\";\n }\n });\n }\n if (this.config.debugAdTiming) {\n console.log(\"[StormcloudVideoPlayer] Showing placeholder layer (between content and ad layer)\");\n }\n }\n hidePlaceholderLayer() {\n if (!this.placeholderContainer) {\n return;\n }\n this.placeholderContainer.style.opacity = \"0\";\n setTimeout(() => {\n if (this.placeholderContainer) {\n this.placeholderContainer.style.display = \"none\";\n this.placeholderContainer.style.pointerEvents = \"none\";\n this.placeholderContainer.style.backgroundColor = \"#000\";\n }\n }, 300);\n if (this.config.debugAdTiming) {\n console.log(\"[StormcloudVideoPlayer] Hiding placeholder layer\");\n }\n }\n attach() {\n if (this.attached) return;\n this.attached = true;\n this.video.autoplay = !!this.config.autoplay;\n this.video.muted = !!this.config.muted;\n this.adPlayer.initialize();\n this.adPlayer.updateOriginalMutedState(this.video.muted, this.video.volume);\n this.attachImaEventListeners();\n this.video.addEventListener(\"play\", () => {\n if (!this.palPlaybackStarted && !this.adPlayer.isAdPlaying()) {\n this.palPlaybackStarted = true;\n this.palNonce.sendPlaybackStart();\n }\n });\n this.video.addEventListener(\"ended\", () => {\n if (this.palPlaybackStarted) {\n this.palPlaybackStarted = false;\n this.palNonce.sendPlaybackEnd();\n }\n });\n this.video.addEventListener(\"mousedown\", (e) => {\n this.palNonce.sendAdTouch(e);\n });\n this.video.addEventListener(\"touchstart\", (e) => {\n this.palNonce.sendAdTouch(e);\n });\n this.timeUpdateHandler = () => {\n this.onTimeUpdate(this.video.currentTime);\n };\n this.video.addEventListener(\"timeupdate\", this.timeUpdateHandler);\n this.emptiedHandler = () => {\n if (this.nativeHlsMode && this.videoSrcProtection && !this.adPlayer.isAdPlaying()) {\n if (this.config.debugAdTiming) {\n console.log(\n \"[StormcloudVideoPlayer] Video src was cleared, restoring:\",\n this.videoSrcProtection\n );\n }\n const currentTime = this.video.currentTime;\n const wasPaused = this.video.paused;\n this.video.src = this.videoSrcProtection;\n this.video.currentTime = currentTime;\n if (!wasPaused) {\n this.video.play().catch(() => {\n });\n }\n }\n };\n this.video.addEventListener(\"emptied\", this.emptiedHandler);\n }\n shouldUseNativeHls() {\n const streamType = this.getStreamType();\n if (streamType === \"other\") {\n return true;\n }\n const canNative = this.video.canPlayType(\"application/vnd.apple.mpegurl\");\n return !!(this.config.allowNativeHls && canNative);\n }\n onId3Tag(tag) {\n if (typeof tag.ptsSeconds === \"number\") {\n this.updatePtsDrift(tag.ptsSeconds);\n }\n const marker = this.parseScte35FromId3(tag);\n if (marker) {\n this.onScte35Cue(marker, {\n source: \"id3\",\n readiness: \"playback\"\n });\n }\n }\n parseScte35FromId3(tag) {\n const text = this.decodeId3ValueToText(tag.value);\n if (!text) return void 0;\n const cueOutMatch = text.match(/EXT-X-CUE-OUT(?::([^\\r\\n]*))?/i) || text.match(/CUE-OUT(?::([^\\r\\n]*))?/i);\n if (cueOutMatch) {\n const arg = (cueOutMatch[1] ?? \"\").trim();\n const dur = this.parseCueOutDuration(arg);\n const marker = {\n type: \"start\",\n ...tag.ptsSeconds !== void 0 ? { ptsSeconds: tag.ptsSeconds } : {},\n ...dur !== void 0 ? { durationSeconds: dur } : {},\n raw: { id3: text }\n };\n return marker;\n }\n const cueOutContMatch = text.match(/EXT-X-CUE-OUT-CONT:([^\\r\\n]*)/i);\n if (cueOutContMatch) {\n const arg = (cueOutContMatch[1] ?? \"\").trim();\n const cont = this.parseCueOutCont(arg);\n const marker = {\n type: \"progress\",\n ...tag.ptsSeconds !== void 0 ? { ptsSeconds: tag.ptsSeconds } : {},\n ...cont?.duration !== void 0 ? { durationSeconds: cont.duration } : {},\n raw: { id3: text }\n };\n return marker;\n }\n const cueInMatch = text.match(/EXT-X-CUE-IN\\b/i) || text.match(/CUE-IN\\b/i);\n if (cueInMatch) {\n const marker = {\n type: \"end\",\n ...tag.ptsSeconds !== void 0 ? { ptsSeconds: tag.ptsSeconds } : {},\n raw: { id3: text }\n };\n return marker;\n }\n const daterangeMatch = text.match(/EXT-X-DATERANGE:([^\\r\\n]*)/i);\n if (daterangeMatch) {\n const attrs = this.parseAttributeList(daterangeMatch[1] ?? \"\");\n const hasScteOut = \"SCTE35-OUT\" in attrs || attrs[\"SCTE35-OUT\"] !== void 0;\n const hasScteIn = \"SCTE35-IN\" in attrs || attrs[\"SCTE35-IN\"] !== void 0;\n const klass = String(attrs[\"CLASS\"] ?? \"\");\n const duration = this.toNumber(attrs[\"DURATION\"]);\n if (hasScteOut || /com\\.apple\\.hls\\.cue/i.test(klass)) {\n const marker = {\n type: \"start\",\n ...tag.ptsSeconds !== void 0 ? { ptsSeconds: tag.ptsSeconds } : {},\n ...duration !== void 0 ? { durationSeconds: duration } : {},\n raw: { id3: text, attrs }\n };\n return marker;\n }\n if (hasScteIn) {\n const marker = {\n type: \"end\",\n ...tag.ptsSeconds !== void 0 ? { ptsSeconds: tag.ptsSeconds } : {},\n raw: { id3: text, attrs }\n };\n return marker;\n }\n }\n if (/SCTE35-OUT/i.test(text)) {\n const marker = {\n type: \"start\",\n ...tag.ptsSeconds !== void 0 ? { ptsSeconds: tag.ptsSeconds } : {},\n raw: { id3: text }\n };\n return marker;\n }\n if (/SCTE35-IN/i.test(text)) {\n const marker = {\n type: \"end\",\n ...tag.ptsSeconds !== void 0 ? { ptsSeconds: tag.ptsSeconds } : {},\n raw: { id3: text }\n };\n return marker;\n }\n if (tag.value instanceof Uint8Array) {\n const bin = this.parseScte35Binary(tag.value);\n if (bin) return bin;\n }\n return void 0;\n }\n decodeId3ValueToText(value) {\n try {\n if (typeof value === \"string\") return value;\n const decoder = new TextDecoder(\"utf-8\", { fatal: false });\n const text = decoder.decode(value);\n if (text && /[\\x20-\\x7E]/.test(text)) return text;\n let out = \"\";\n for (let i = 0; i < value.length; i++)\n out += String.fromCharCode(value[i]);\n return out;\n } catch {\n return void 0;\n }\n }\n createScte35CueContext(source, readiness, frag) {\n const context = { source, readiness };\n if (typeof frag?.sn === \"number\") {\n context.fragmentSn = frag.sn;\n }\n const fragmentStartSeconds = this.getFragmentStartSeconds(frag);\n if (fragmentStartSeconds !== void 0) {\n context.fragmentStartSeconds = fragmentStartSeconds;\n }\n return context;\n }\n getFragmentStartSeconds(frag) {\n const candidates = [frag?.start, frag?.startPTS];\n for (const candidate of candidates) {\n if (typeof candidate === \"number\" && Number.isFinite(candidate)) {\n return candidate;\n }\n }\n return void 0;\n }\n onScte35Cue(marker, context) {\n const cue = this.createScte35Cue(marker, context);\n const pendingKey = this.getPendingScte35CueKey(cue);\n if (context.readiness === \"early\") {\n this.pendingScte35Cues.set(pendingKey, cue);\n this.trimRecentScte35CueMaps();\n if (marker.type === \"start\") {\n this.startAdPrefetch(marker, context.fragmentSn, cue.key);\n }\n return;\n }\n if (marker.type === \"end\" && !this.shouldAcceptScte35EndCue(cue)) {\n if (this.config.debugAdTiming) {\n console.log(\"[StormcloudVideoPlayer] Ignoring SCTE-35 end cue\", {\n key: cue.key,\n activeScte35BreakKey: this.activeScte35BreakKey,\n inAdBreak: this.inAdBreak,\n source: cue.source\n });\n }\n return;\n }\n if (marker.type === \"start\" && this.hasRecentlyHandledScte35Cue(cue)) {\n if (this.config.debugAdTiming) {\n console.log(\"[StormcloudVideoPlayer] Ignoring duplicate SCTE-35 start cue\", {\n key: cue.key,\n source: cue.source\n });\n }\n return;\n }\n this.pendingScte35Cues.delete(pendingKey);\n this.markScte35CueHandled(cue);\n this.onScte35Marker(marker, cue.key);\n }\n createScte35Cue(marker, context) {\n const cue = {\n marker,\n source: context.source,\n readiness: context.readiness,\n key: this.getScte35CueKey(marker, context)\n };\n if (context.fragmentSn !== void 0) {\n cue.fragmentSn = context.fragmentSn;\n }\n if (context.fragmentStartSeconds !== void 0) {\n cue.fragmentStartSeconds = context.fragmentStartSeconds;\n }\n return cue;\n }\n getScte35CueKey(marker, context) {\n const raw = this.getScte35MarkerRaw(marker);\n const spliceEventId = this.toIdentityString(raw?.splice_event_id);\n if (spliceEventId) {\n return `splice:${spliceEventId}`;\n }\n const segmentationEventId = this.toIdentityString(raw?.segmentation_event_id);\n if (segmentationEventId) {\n return `segmentation:${segmentationEventId}`;\n }\n const daterangeId = this.toIdentityString(raw?.attrs?.ID);\n if (daterangeId) {\n return `daterange:${daterangeId}`;\n }\n const scteValue = this.toIdentityString(raw?.attrs?.[\"SCTE35-OUT\"]) || this.toIdentityString(raw?.attrs?.[\"SCTE35-IN\"]);\n if (scteValue) {\n return `daterange-scte:${scteValue}`;\n }\n if (typeof marker.ptsSeconds === \"number\" && Number.isFinite(marker.ptsSeconds)) {\n return `pts:${Math.round(marker.ptsSeconds * 2) / 2}`;\n }\n if (context.fragmentSn !== void 0) {\n return `fragment:${context.fragmentSn}`;\n }\n return `${context.source}:wallclock:${Math.floor(Date.now() / 1e3)}`;\n }\n getPendingScte35CueKey(cue) {\n return `${cue.marker.type}:${cue.key}:${cue.fragmentSn !== void 0 ? cue.fragmentSn : \"unknown\"}`;\n }\n getScte35MarkerRaw(marker) {\n return typeof marker.raw === \"object\" && marker.raw !== null ? marker.raw : {};\n }\n toIdentityString(value) {\n if (typeof value === \"number\" && Number.isFinite(value)) {\n return String(value);\n }\n if (typeof value === \"string\" && value.trim().length > 0) {\n return value.trim();\n }\n return void 0;\n }\n isStrongScte35CueKey(key) {\n return !!(key && (key.startsWith(\"splice:\") || key.startsWith(\"segmentation:\") || key.startsWith(\"daterange:\") || key.startsWith(\"daterange-scte:\")));\n }\n hasRecentlyHandledScte35Cue(cue) {\n if (this.activeScte35BreakKey === cue.key || this.scheduledScte35BreakKey === cue.key) {\n return true;\n }\n const recentKey = `${cue.marker.type}:${cue.key}`;\n return this.recentScte35CueKeys.has(recentKey);\n }\n markScte35CueHandled(cue) {\n this.recentScte35CueKeys.set(`${cue.marker.type}:${cue.key}`, Date.now());\n this.trimRecentScte35CueMaps();\n }\n trimRecentScte35CueMaps() {\n while (this.recentScte35CueKeys.size > this.recentScte35CueLimit) {\n const firstKey = this.recentScte35CueKeys.keys().next().value;\n if (!firstKey) {\n break;\n }\n this.recentScte35CueKeys.delete(firstKey);\n }\n while (this.pendingScte35Cues.size > this.recentScte35CueLimit) {\n const firstKey = this.pendingScte35Cues.keys().next().value;\n if (!firstKey) {\n break;\n }\n this.pendingScte35Cues.delete(firstKey);\n }\n }\n shouldAcceptScte35EndCue(cue) {\n if (!this.inAdBreak) {\n return false;\n }\n if (this.isStrongScte35CueKey(this.activeScte35BreakKey) && this.isStrongScte35CueKey(cue.key) && this.activeScte35BreakKey !== cue.key) {\n return false;\n }\n return true;\n }\n activatePendingScte35CuesForFragment(frag) {\n const fragmentSn = typeof frag?.sn === \"number\" ? frag.sn : void 0;\n if (fragmentSn === void 0) {\n return;\n }\n const matchingCues = Array.from(this.pendingScte35Cues.entries()).filter(\n ([, cue]) => cue.fragmentSn === fragmentSn\n );\n matchingCues.forEach(([pendingKey, cue]) => {\n this.pendingScte35Cues.delete(pendingKey);\n const context = {\n source: cue.source,\n readiness: \"playback\"\n };\n context.fragmentSn = fragmentSn;\n const fragmentStartSeconds = cue.fragmentStartSeconds ?? this.getFragmentStartSeconds(frag);\n if (fragmentStartSeconds !== void 0) {\n context.fragmentStartSeconds = fragmentStartSeconds;\n }\n this.onScte35Cue(cue.marker, context);\n });\n }\n onScte35Marker(marker, cueKey) {\n if (this.config.debugAdTiming) {\n console.log(\"[StormcloudVideoPlayer] SCTE-35 marker detected:\", {\n type: marker.type,\n ptsSeconds: marker.ptsSeconds,\n durationSeconds: marker.durationSeconds,\n currentTime: this.video.currentTime,\n raw: marker.raw,\n hasPendingAdBreak: !!this.pendingAdBreak\n });\n }\n if (marker.type === \"start\") {\n if (this.inAdBreak) {\n if (marker.durationSeconds != null) {\n const newDurationMs = marker.durationSeconds * 1e3;\n if (this.expectedAdBreakDurationMs == null || newDurationMs > this.expectedAdBreakDurationMs) {\n this.expectedAdBreakDurationMs = newDurationMs;\n const elapsedMs = this.currentAdBreakStartWallClockMs != null ? Date.now() - this.currentAdBreakStartWallClockMs : 0;\n const remainingMs = Math.max(0, newDurationMs - elapsedMs);\n this.scheduleAdStopCountdown(remainingMs);\n if (this.config.debugAdTiming) {\n console.log(\n `[StormcloudVideoPlayer] Updated ad break duration from subsequent marker: ${newDurationMs}ms, remaining: ${remainingMs}ms`\n );\n }\n }\n }\n return;\n }\n if (!this.adDetectSentForCurrentBreak) {\n this.adDetectSentForCurrentBreak = true;\n const detectPayload = {};\n if (marker.durationSeconds != null) detectPayload.durationSeconds = marker.durationSeconds;\n if (marker.ptsSeconds != null) detectPayload.ptsSeconds = marker.ptsSeconds;\n sendAdDetectTracking(this.config.licenseKey, { source: \"scte35\", timestamp: (/* @__PURE__ */ new Date()).toISOString(), ...detectPayload }).catch(() => {\n });\n }\n const hasPrefetchedAds = this.pendingAdBreak && this.pendingAdBreak.vastUrls.length > 0;\n const durationMs = marker.durationSeconds != null ? marker.durationSeconds * 1e3 : this.pendingAdBreak?.marker.durationSeconds != null ? this.pendingAdBreak.marker.durationSeconds * 1e3 : void 0;\n const isManifestMarker = this.isManifestBasedMarker(marker);\n const forceImmediate = this.config.immediateManifestAds ?? true;\n if (this.config.debugAdTiming) {\n console.log(\"[StormcloudVideoPlayer] Ad start decision:\", {\n isManifestMarker,\n forceImmediate,\n hasPts: typeof marker.ptsSeconds === \"number\",\n hasPrefetchedAds\n });\n }\n if (isManifestMarker && forceImmediate) {\n if (this.config.debugAdTiming) {\n console.log(\n `[StormcloudVideoPlayer] Starting ad immediately (manifest-based)${hasPrefetchedAds ? \" with prefetched ads\" : \"\"}`\n );\n }\n this.clearAdStartTimer();\n this.startScte35AdBreak(marker, cueKey, durationMs);\n } else if (typeof marker.ptsSeconds === \"number\") {\n const tol = this.config.driftToleranceMs ?? 1e3;\n const nowMs = this.video.currentTime * 1e3;\n const estCurrentPtsMs = nowMs - this.ptsDriftEmaMs;\n const deltaMs = Math.floor(marker.ptsSeconds * 1e3 - estCurrentPtsMs);\n if (this.config.debugAdTiming) {\n console.log(\"[StormcloudVideoPlayer] PTS-based timing calculation:\", {\n nowMs,\n estCurrentPtsMs,\n markerPtsMs: marker.ptsSeconds * 1e3,\n deltaMs,\n tolerance: tol\n });\n }\n if (deltaMs > tol) {\n if (this.config.debugAdTiming) {\n console.log(\n `[StormcloudVideoPlayer] Scheduling ad start in ${deltaMs}ms`\n );\n }\n this.expectedAdBreakDurationMs = durationMs;\n this.scheduledScte35BreakKey = cueKey;\n this.scheduleAdStartIn(deltaMs, marker, cueKey);\n } else {\n if (this.config.debugAdTiming) {\n console.log(\n \"[StormcloudVideoPlayer] Starting ad immediately (within tolerance)\"\n );\n }\n this.clearAdStartTimer();\n this.startScte35AdBreak(marker, cueKey, durationMs);\n }\n } else {\n if (this.config.debugAdTiming) {\n console.log(\n \"[StormcloudVideoPlayer] Starting ad immediately (fallback)\"\n );\n }\n this.clearAdStartTimer();\n this.startScte35AdBreak(marker, cueKey, durationMs);\n }\n return;\n }\n if (marker.type === \"progress\" && this.inAdBreak) {\n if (marker.durationSeconds != null) {\n this.expectedAdBreakDurationMs = marker.durationSeconds * 1e3;\n }\n if (this.expectedAdBreakDurationMs != null && this.currentAdBreakStartWallClockMs != null) {\n const elapsedMs = Date.now() - this.currentAdBreakStartWallClockMs;\n const remainingMs = Math.max(\n 0,\n this.expectedAdBreakDurationMs - elapsedMs\n );\n this.scheduleAdStopCountdown(remainingMs);\n }\n if (!this.adPlayer.isAdPlaying() && this.activeAdRequestToken === null && this.adRequestQueue.length > 0) {\n this.tryNextAvailableAdWithRateLimit();\n }\n return;\n }\n if (marker.type === \"end\") {\n if (!this.video.muted) {\n this.video.muted = true;\n this.video.volume = 0;\n if (this.config.debugAdTiming) {\n console.log(\"[StormcloudVideoPlayer] Muted video on SCTE end marker\");\n }\n }\n const remaining = this.getRemainingAdMs();\n const adPlaying = this.adPlayer.isAdPlaying();\n const hasQueuedAds = this.adRequestQueue.length > 0;\n if (this.config.debugAdTiming) {\n console.log(\"[StormcloudVideoPlayer] SCTE-35 end marker received:\", {\n remaining,\n adPlaying,\n hasQueuedAds,\n activeAdRequest: this.activeAdRequestToken !== null\n });\n }\n if (adPlaying || remaining > 1e3 && hasQueuedAds) {\n if (this.config.debugAdTiming) {\n console.log(\"[StormcloudVideoPlayer] Ignoring premature SCTE-35 end marker - ads still active\");\n }\n return;\n }\n this.inAdBreak = false;\n this.expectedAdBreakDurationMs = void 0;\n this.currentAdBreakStartWallClockMs = void 0;\n this.clearAdStartTimer();\n this.clearAdStopTimer();\n if (adPlaying) {\n this.adPlayer.stop().catch(() => {\n });\n }\n this.handleAdPodComplete();\n return;\n }\n }\n startScte35AdBreak(marker, cueKey, durationMs) {\n if (!this.video.muted) {\n this.video.muted = true;\n this.video.volume = 0;\n if (this.config.debugAdTiming) {\n console.log(\"[StormcloudVideoPlayer] Muted video on SCTE start marker\");\n }\n }\n this.inAdBreak = true;\n this.activeScte35BreakKey = cueKey ?? this.pendingScte35CueKey;\n this.scheduledScte35BreakKey = void 0;\n this.expectedAdBreakDurationMs = durationMs;\n this.currentAdBreakStartWallClockMs = Date.now();\n this.handleAdStart(marker);\n if (this.expectedAdBreakDurationMs != null) {\n this.scheduleAdStopCountdown(this.expectedAdBreakDurationMs);\n }\n }\n parseCueOutDuration(value) {\n const num = parseFloat(value.trim());\n if (!Number.isNaN(num)) return num;\n const match = value.match(/(?:^|[,\\s])DURATION\\s*=\\s*([0-9.]+)/i) || value.match(/Duration\\s*=\\s*([0-9.]+)/i);\n if (match && match[1] != null) {\n const dStr = match[1];\n const d = parseFloat(dStr);\n return Number.isNaN(d) ? void 0 : d;\n }\n return void 0;\n }\n parseCueOutCont(value) {\n const res = {};\n const elapsedMatch = value.match(/Elapsed\\s*=\\s*([0-9.]+)/i);\n const durationMatch = value.match(/Duration\\s*=\\s*([0-9.]+)/i);\n if (elapsedMatch && elapsedMatch[1] != null) {\n const e = parseFloat(elapsedMatch[1]);\n if (!Number.isNaN(e)) res.elapsed = e;\n }\n if (durationMatch && durationMatch[1] != null) {\n const d = parseFloat(durationMatch[1]);\n if (!Number.isNaN(d)) res.duration = d;\n }\n if (!(\"elapsed\" in res) || !(\"duration\" in res)) {\n const slashMatch = value.match(/([0-9.]+)\\s*\\/\\s*([0-9.]+)/);\n if (slashMatch && slashMatch[1] && slashMatch[2]) {\n const elapsed = parseFloat(slashMatch[1]);\n const duration = parseFloat(slashMatch[2]);\n if (!Number.isNaN(elapsed) && !(\"elapsed\" in res)) res.elapsed = elapsed;\n if (!Number.isNaN(duration) && !(\"duration\" in res)) res.duration = duration;\n }\n }\n if (\"elapsed\" in res || \"duration\" in res) return res;\n return void 0;\n }\n parseAttributeList(value) {\n const attrs = {};\n const regex = /([A-Z0-9-]+)=((\"[^\"]*\")|([^\",]*))(?:,|$)/gi;\n let match;\n while ((match = regex.exec(value)) !== null) {\n const key = match[1] ?? \"\";\n let rawVal = match[3] ?? match[4] ?? \"\";\n if (rawVal.startsWith('\"') && rawVal.endsWith('\"')) {\n rawVal = rawVal.slice(1, -1);\n }\n if (key) {\n attrs[key] = rawVal;\n }\n }\n return attrs;\n }\n toNumber(val) {\n if (val == null) return void 0;\n const n = typeof val === \"string\" ? parseFloat(val) : Number(val);\n return Number.isNaN(n) ? void 0 : n;\n }\n isManifestBasedMarker(marker) {\n const raw = marker.raw;\n if (!raw) return false;\n if (raw.tag) {\n const tag = String(raw.tag);\n return tag.includes(\"EXT-X-CUE-OUT\") || tag.includes(\"EXT-X-CUE-IN\") || tag.includes(\"EXT-X-DATERANGE\");\n }\n if (raw.id3) return false;\n if (raw.splice_command_type) return false;\n return false;\n }\n normalizeFragmentPayload(payload) {\n if (payload instanceof Uint8Array) {\n return payload;\n }\n if (payload instanceof ArrayBuffer) {\n return new Uint8Array(payload);\n }\n if (ArrayBuffer.isView(payload)) {\n const view = payload;\n return new Uint8Array(view.buffer, view.byteOffset, view.byteLength);\n }\n return void 0;\n }\n processFragmentScte35Payload(payloadData, fragmentSn, fragmentStartSeconds) {\n const payload = this.normalizeFragmentPayload(payloadData);\n if (!payload) {\n return;\n }\n const markers = this.parseScte35FromTsPackets(payload);\n markers.forEach((marker) => {\n const context = {\n source: \"ts\",\n readiness: \"early\"\n };\n if (fragmentSn !== void 0) {\n context.fragmentSn = fragmentSn;\n }\n if (fragmentStartSeconds !== void 0) {\n context.fragmentStartSeconds = fragmentStartSeconds;\n }\n this.onScte35Cue(marker, context);\n });\n }\n parseScte35FromTsPackets(data) {\n const packetInfo = this.detectTsPacketFormat(data);\n if (!packetInfo) {\n return [];\n }\n const markers = [];\n const sectionAssemblers = /* @__PURE__ */ new Map();\n for (let packetStart = packetInfo.offset; packetStart + packetInfo.packetSize <= data.length; packetStart += packetInfo.packetSize) {\n const tsStart = packetStart + packetInfo.tsPayloadOffset;\n if (data[tsStart] !== 71) {\n continue;\n }\n const secondByte = data[tsStart + 1];\n const thirdByte = data[tsStart + 2];\n const fourthByte = data[tsStart + 3];\n if (secondByte == null || thirdByte == null || fourthByte == null || (secondByte & 128) !== 0) {\n continue;\n }\n const payloadUnitStart = (secondByte & 64) !== 0;\n const pid = (secondByte & 31) << 8 | thirdByte;\n const adaptationFieldControl = fourthByte >> 4 & 3;\n const hasPayload = adaptationFieldControl === 1 || adaptationFieldControl === 3;\n if (!hasPayload) {\n continue;\n }\n let payloadStart = tsStart + 4;\n if (adaptationFieldControl === 3) {\n const adaptationLength = data[payloadStart];\n if (adaptationLength == null) {\n continue;\n }\n payloadStart += 1 + adaptationLength;\n }\n const payloadEnd = Math.min(tsStart + 188, data.length);\n if (payloadStart >= payloadEnd || payloadStart >= data.length) {\n continue;\n }\n const payload = data.subarray(payloadStart, payloadEnd);\n if (pid === 0) {\n this.parsePatSection(payload, payloadUnitStart);\n } else if (this.pmtPids.has(pid)) {\n this.parsePmtSection(payload, payloadUnitStart);\n } else if (this.tsScte35Pids.has(pid)) {\n this.collectScte35SectionsFromPayload(\n pid,\n payload,\n payloadUnitStart,\n sectionAssemblers,\n markers\n );\n }\n }\n return markers;\n }\n detectTsPacketFormat(data) {\n const packetSizes = [188, 192, 204];\n for (const packetSize of packetSizes) {\n const tsPayloadOffset = packetSize === 192 ? 4 : 0;\n for (let offset = 0; offset < packetSize; offset++) {\n let matchedPackets = 0;\n for (let packetStart = offset; packetStart + tsPayloadOffset < data.length && matchedPackets < 5; packetStart += packetSize) {\n if (data[packetStart + tsPayloadOffset] !== 71) {\n break;\n }\n matchedPackets++;\n }\n if (matchedPackets >= 2) {\n return { offset, packetSize, tsPayloadOffset };\n }\n }\n }\n return void 0;\n }\n parsePatSection(payload, payloadUnitStart) {\n const sectionStart = this.getPsiSectionStart(payload, payloadUnitStart);\n if (sectionStart == null || sectionStart + 8 >= payload.length) {\n return;\n }\n if (payload[sectionStart] !== 0) {\n return;\n }\n const sectionLength = this.getPsiSectionLength(payload, sectionStart);\n const sectionEnd = Math.min(\n payload.length,\n sectionStart + 3 + sectionLength\n );\n for (let offset = sectionStart + 8; offset + 4 <= sectionEnd - 4; offset += 4) {\n const programNumber = (payload[offset] ?? 0) << 8 | (payload[offset + 1] ?? 0);\n const pid = ((payload[offset + 2] ?? 0) & 31) << 8 | (payload[offset + 3] ?? 0);\n if (programNumber !== 0) {\n this.pmtPids.add(pid);\n }\n }\n }\n parsePmtSection(payload, payloadUnitStart) {\n const sectionStart = this.getPsiSectionStart(payload, payloadUnitStart);\n if (sectionStart == null || sectionStart + 12 >= payload.length) {\n return;\n }\n if (payload[sectionStart] !== 2) {\n return;\n }\n const sectionLength = this.getPsiSectionLength(payload, sectionStart);\n const sectionEnd = Math.min(\n payload.length,\n sectionStart + 3 + sectionLength\n );\n const programInfoLength = ((payload[sectionStart + 10] ?? 0) & 15) << 8 | (payload[sectionStart + 11] ?? 0);\n let offset = sectionStart + 12 + programInfoLength;\n while (offset + 5 <= sectionEnd - 4) {\n const streamType = payload[offset] ?? 0;\n const elementaryPid = ((payload[offset + 1] ?? 0) & 31) << 8 | (payload[offset + 2] ?? 0);\n const esInfoLength = ((payload[offset + 3] ?? 0) & 15) << 8 | (payload[offset + 4] ?? 0);\n const descriptorStart = offset + 5;\n const descriptorEnd = Math.min(descriptorStart + esInfoLength, sectionEnd - 4);\n if (streamType === 134 || streamType === 6 && this.descriptorsIdentifyScte35(payload, descriptorStart, descriptorEnd)) {\n this.tsScte35Pids.add(elementaryPid);\n }\n offset = descriptorStart + esInfoLength;\n }\n }\n descriptorsIdentifyScte35(data, start, end) {\n let offset = start;\n while (offset + 2 <= end) {\n const tag = data[offset] ?? 0;\n const length = data[offset + 1] ?? 0;\n const descriptorStart = offset + 2;\n const descriptorEnd = descriptorStart + length;\n if (descriptorEnd > end) {\n return false;\n }\n const registration = length >= 4 ? String.fromCharCode(\n data[descriptorStart] ?? 0,\n data[descriptorStart + 1] ?? 0,\n data[descriptorStart + 2] ?? 0,\n data[descriptorStart + 3] ?? 0\n ) : \"\";\n if (tag === 138 || registration === \"CUEI\" || registration === \"SCTE\") {\n return true;\n }\n offset = descriptorEnd;\n }\n return false;\n }\n collectScte35SectionsFromPayload(pid, payload, payloadUnitStart, assemblers, markers) {\n if (payload.length === 0) {\n return;\n }\n let offset = 0;\n if (payloadUnitStart) {\n const pointerField = payload[0] ?? 0;\n const previousAssembler = assemblers.get(pid);\n if (previousAssembler && pointerField > 0) {\n this.appendScte35Bytes(\n pid,\n payload.subarray(1, Math.min(1 + pointerField, payload.length)),\n assemblers,\n markers\n );\n }\n assemblers.delete(pid);\n offset = 1 + pointerField;\n } else {\n this.appendScte35Bytes(pid, payload, assemblers, markers);\n return;\n }\n while (offset + 3 <= payload.length) {\n const tableId = payload[offset];\n if (tableId == null || tableId === 255) {\n return;\n }\n const sectionLength = this.getPsiSectionLength(payload, offset);\n const totalLength = 3 + sectionLength;\n if (sectionLength <= 0 || totalLength <= 3) {\n return;\n }\n if (offset + totalLength <= payload.length) {\n this.addScte35SectionMarker(\n payload.subarray(offset, offset + totalLength),\n markers\n );\n offset += totalLength;\n } else {\n assemblers.set(pid, {\n bytes: Array.from(payload.subarray(offset)),\n expectedLength: totalLength\n });\n return;\n }\n }\n }\n appendScte35Bytes(pid, bytes, assemblers, markers) {\n const assembler = assemblers.get(pid);\n if (!assembler) {\n return;\n }\n for (let i = 0; i < bytes.length && assembler.bytes.length < assembler.expectedLength; i++) {\n assembler.bytes.push(bytes[i] ?? 0);\n }\n if (assembler.bytes.length >= assembler.expectedLength) {\n assemblers.delete(pid);\n this.addScte35SectionMarker(new Uint8Array(assembler.bytes), markers);\n }\n }\n addScte35SectionMarker(section, markers) {\n if (section[0] !== 252 || this.hasProcessedTsScte35Section(section)) {\n return;\n }\n const marker = this.parseScte35Binary(section);\n if (!marker) {\n return;\n }\n marker.raw = {\n ...typeof marker.raw === \"object\" && marker.raw ? marker.raw : {},\n source: \"ts-packet\"\n };\n markers.push(marker);\n }\n hasProcessedTsScte35Section(section) {\n let checksum = 0;\n for (let i = 0; i < section.length; i++) {\n checksum = checksum * 31 + (section[i] ?? 0) >>> 0;\n }\n const key = `${section.length}:${checksum}`;\n if (this.processedTsScte35Sections.has(key)) {\n return true;\n }\n this.processedTsScte35Sections.add(key);\n if (this.processedTsScte35Sections.size > 200) {\n const firstKey = this.processedTsScte35Sections.values().next().value;\n if (firstKey) {\n this.processedTsScte35Sections.delete(firstKey);\n }\n }\n return false;\n }\n getPsiSectionStart(payload, payloadUnitStart) {\n if (!payloadUnitStart) {\n return void 0;\n }\n const pointerField = payload[0];\n if (pointerField == null) {\n return void 0;\n }\n const sectionStart = 1 + pointerField;\n return sectionStart < payload.length ? sectionStart : void 0;\n }\n getPsiSectionLength(data, offset) {\n return ((data[offset + 1] ?? 0) & 15) << 8 | (data[offset + 2] ?? 0);\n }\n parseScte35Binary(data) {\n class BitReader {\n constructor(buf) {\n this.buf = buf;\n this.bytePos = 0;\n this.bitPos = 0;\n }\n readBits(numBits) {\n let result = 0;\n while (numBits > 0) {\n if (this.bytePos >= this.buf.length) return result;\n const remainingInByte = 8 - this.bitPos;\n const toRead = Math.min(numBits, remainingInByte);\n const currentByte = this.buf[this.bytePos];\n const shift = remainingInByte - toRead;\n const mask = (1 << toRead) - 1 & 255;\n const bits = currentByte >> shift & mask;\n result = result << toRead | bits;\n this.bitPos += toRead;\n if (this.bitPos >= 8) {\n this.bitPos = 0;\n this.bytePos += 1;\n }\n numBits -= toRead;\n }\n return result >>> 0;\n }\n skipBits(n) {\n this.readBits(n);\n }\n get bytePosition() {\n return this.bitPos === 0 ? this.bytePos : this.bytePos + 1;\n }\n }\n const readSpliceTime = (r2, ptsAdjustmentTicks2) => {\n const timeSpecifiedFlag = r2.readBits(1) === 1;\n if (!timeSpecifiedFlag) {\n r2.readBits(7);\n return void 0;\n }\n r2.readBits(6);\n const high = r2.readBits(1);\n const low = r2.readBits(32);\n const ptsTicks = (high * 4294967296 + low + ptsAdjustmentTicks2) % 8589934592;\n return ptsTicks / 9e4;\n };\n const r = new BitReader(data);\n const tableId = r.readBits(8);\n if (tableId !== 252) return void 0;\n r.readBits(1);\n r.readBits(1);\n r.readBits(2);\n const sectionLength = r.readBits(12);\n if (sectionLength <= 0 || data.length < 3 + sectionLength) {\n return void 0;\n }\n r.readBits(8);\n r.readBits(1);\n r.readBits(6);\n const ptsAdjHigh = r.readBits(1);\n const ptsAdjLow = r.readBits(32);\n const ptsAdjustmentTicks = ptsAdjHigh * 4294967296 + ptsAdjLow;\n r.readBits(8);\n r.readBits(12);\n const spliceCommandLength = r.readBits(12);\n const spliceCommandType = r.readBits(8);\n let markerType;\n let durationSeconds = void 0;\n let ptsSeconds = void 0;\n let spliceEventId = void 0;\n const commandBodyStart = r.bytePosition;\n if (spliceCommandType === 5) {\n spliceEventId = r.readBits(32);\n const cancel = r.readBits(1) === 1;\n r.readBits(7);\n if (cancel) return void 0;\n const outOfNetwork = r.readBits(1) === 1;\n const programSpliceFlag = r.readBits(1) === 1;\n const durationFlag = r.readBits(1) === 1;\n const spliceImmediateFlag = r.readBits(1) === 1;\n r.readBits(4);\n markerType = outOfNetwork ? \"start\" : \"end\";\n if (programSpliceFlag && !spliceImmediateFlag) {\n ptsSeconds = readSpliceTime(r, ptsAdjustmentTicks);\n } else if (!programSpliceFlag) {\n const componentCount = r.readBits(8);\n for (let i = 0; i < componentCount; i++) {\n r.readBits(8);\n if (!spliceImmediateFlag) {\n const componentPtsSeconds = readSpliceTime(r, ptsAdjustmentTicks);\n if (ptsSeconds === void 0) {\n ptsSeconds = componentPtsSeconds;\n }\n }\n }\n }\n if (durationFlag) {\n r.readBits(6);\n r.readBits(1);\n const high = r.readBits(1);\n const low = r.readBits(32);\n const durationTicks = high * 4294967296 + low;\n durationSeconds = durationTicks / 9e4;\n }\n r.readBits(16);\n r.readBits(8);\n r.readBits(8);\n } else if (spliceCommandType === 6) {\n ptsSeconds = readSpliceTime(r, ptsAdjustmentTicks);\n } else {\n return void 0;\n }\n const expectedDescriptorOffset = spliceCommandLength === 4095 ? r.bytePosition : commandBodyStart + spliceCommandLength;\n const descriptorMarker = this.parseScte35SegmentationDescriptors(\n data,\n expectedDescriptorOffset\n );\n if (descriptorMarker) {\n markerType = descriptorMarker.type;\n if (durationSeconds === void 0) {\n durationSeconds = descriptorMarker.durationSeconds;\n }\n }\n if (!markerType) {\n return void 0;\n }\n const marker = {\n type: markerType,\n ...ptsSeconds !== void 0 ? { ptsSeconds } : {},\n ...durationSeconds !== void 0 ? { durationSeconds } : {},\n raw: {\n splice_command_type: spliceCommandType,\n ...spliceEventId !== void 0 ? { splice_event_id: spliceEventId } : {},\n ...descriptorMarker?.segmentationEventId !== void 0 ? { segmentation_event_id: descriptorMarker.segmentationEventId } : {}\n }\n };\n return marker;\n }\n parseScte35SegmentationDescriptors(data, offset) {\n if (offset + 2 > data.length) {\n return void 0;\n }\n const descriptorLoopLength = (data[offset] ?? 0) << 8 | (data[offset + 1] ?? 0);\n let descriptorOffset = offset + 2;\n const descriptorEnd = Math.min(\n data.length,\n descriptorOffset + descriptorLoopLength\n );\n while (descriptorOffset + 2 <= descriptorEnd) {\n const descriptorTag = data[descriptorOffset] ?? 0;\n const descriptorLength = data[descriptorOffset + 1] ?? 0;\n const descriptorDataStart = descriptorOffset + 2;\n const descriptorDataEnd = descriptorDataStart + descriptorLength;\n if (descriptorDataEnd > descriptorEnd) {\n return void 0;\n }\n if (descriptorTag === 2) {\n const descriptorMarker = this.parseScte35SegmentationDescriptor(\n data.subarray(descriptorDataStart, descriptorDataEnd)\n );\n if (descriptorMarker) {\n return descriptorMarker;\n }\n }\n descriptorOffset = descriptorDataEnd;\n }\n return void 0;\n }\n parseScte35SegmentationDescriptor(descriptor) {\n if (descriptor.length < 11) {\n return void 0;\n }\n const identifier = String.fromCharCode(\n descriptor[0] ?? 0,\n descriptor[1] ?? 0,\n descriptor[2] ?? 0,\n descriptor[3] ?? 0\n );\n if (identifier !== \"CUEI\") {\n return void 0;\n }\n const segmentationEventId = (descriptor[4] ?? 0) * 16777216 + ((descriptor[5] ?? 0) << 16) + ((descriptor[6] ?? 0) << 8) + (descriptor[7] ?? 0);\n const cancelIndicator = ((descriptor[8] ?? 0) & 128) !== 0;\n if (cancelIndicator) {\n return void 0;\n }\n const flags = descriptor[9] ?? 0;\n const programSegmentationFlag = (flags & 128) !== 0;\n const segmentationDurationFlag = (flags & 64) !== 0;\n let offset = 10;\n if (!programSegmentationFlag) {\n const componentCount = descriptor[offset] ?? 0;\n offset += 1 + componentCount * 6;\n if (offset > descriptor.length) {\n return void 0;\n }\n }\n let durationSeconds = void 0;\n if (segmentationDurationFlag) {\n if (offset + 5 > descriptor.length) {\n return void 0;\n }\n const durationTicks = (descriptor[offset] ?? 0) * 4294967296 + (descriptor[offset + 1] ?? 0) * 16777216 + ((descriptor[offset + 2] ?? 0) << 16) + ((descriptor[offset + 3] ?? 0) << 8) + (descriptor[offset + 4] ?? 0);\n durationSeconds = durationTicks / 9e4;\n offset += 5;\n }\n if (offset + 2 > descriptor.length) {\n return void 0;\n }\n offset += 1;\n const segmentationUpidLength = descriptor[offset] ?? 0;\n offset += 1 + segmentationUpidLength;\n if (offset >= descriptor.length) {\n return void 0;\n }\n const segmentationTypeId = descriptor[offset] ?? 0;\n const markerType = this.markerTypeFromSegmentationTypeId(segmentationTypeId);\n if (!markerType) {\n return void 0;\n }\n return {\n type: markerType,\n ...durationSeconds !== void 0 ? { durationSeconds } : {},\n segmentationEventId\n };\n }\n markerTypeFromSegmentationTypeId(segmentationTypeId) {\n switch (segmentationTypeId) {\n case 16:\n case 34:\n case 48:\n case 50:\n case 52:\n case 54:\n return \"start\";\n case 17:\n case 35:\n case 49:\n case 51:\n case 53:\n case 55:\n return \"end\";\n default:\n return void 0;\n }\n }\n initializeTracking() {\n sendInitialTracking(this.config.licenseKey).then(() => {\n this.heartbeatInterval = window.setInterval(() => {\n this.sendHeartbeatIfNeeded();\n }, 5e3);\n }).catch((error) => {\n if (this.config.debugAdTiming) {\n console.warn(\n \"[StormcloudVideoPlayer] Failed to send initial tracking:\",\n error\n );\n }\n this.heartbeatInterval = window.setInterval(() => {\n this.sendHeartbeatIfNeeded();\n }, 5e3);\n });\n }\n sendHeartbeatIfNeeded() {\n const now = Date.now();\n if (!this.lastHeartbeatTime || now - this.lastHeartbeatTime > 3e4) {\n this.lastHeartbeatTime = now;\n sendHeartbeat(this.config.licenseKey).catch((error) => {\n if (this.config.debugAdTiming) {\n console.warn(\n \"[StormcloudVideoPlayer] Failed to send heartbeat:\",\n error\n );\n }\n });\n }\n }\n async fetchAdConfiguration() {\n if (this.config.vmapUrl) {\n await this.fetchAndParseVmap(this.config.vmapUrl);\n }\n const vastMode = this.config.vastMode || \"default\";\n if (this.config.debugAdTiming) {\n console.log(\"[StormcloudVideoPlayer] VAST mode:\", vastMode);\n }\n if (vastMode === \"adstorm\") {\n if (!this.config.licenseKey) {\n if (this.config.debugAdTiming) {\n console.warn(\n \"[StormcloudVideoPlayer] AdStorm mode requires a license key\"\n );\n }\n return;\n }\n const vastEndpoint = `https://adstorm.co/api-adstorm-dev/adstorm/vast/${this.config.licenseKey}`;\n this.apiVastTagUrl = vastEndpoint;\n if (this.config.debugAdTiming) {\n console.log(\n \"[StormcloudVideoPlayer] Using AdStorm VAST endpoint (adstorm mode):\",\n vastEndpoint\n );\n }\n return;\n }\n if (this.config.vastTagUrl) {\n this.apiVastTagUrl = this.config.vastTagUrl;\n if (this.config.debugAdTiming) {\n console.log(\n \"[StormcloudVideoPlayer] Using custom VAST tag URL:\",\n this.apiVastTagUrl\n );\n }\n return;\n }\n const apiUrl = \"https://adstorm.co/api-adstorm-dev/adstorm/ads/web\";\n if (this.config.debugAdTiming) {\n console.log(\n \"[StormcloudVideoPlayer] Fetching ad configuration from:\",\n apiUrl\n );\n }\n const headers = {};\n if (this.config.licenseKey) {\n headers[\"Authorization\"] = `Bearer ${this.config.licenseKey}`;\n }\n const response = await fetch(apiUrl, { headers });\n if (!response.ok) {\n if (this.config.debugAdTiming) {\n console.warn(\n `[StormcloudVideoPlayer] Failed to fetch ad configuration: ${response.status}`\n );\n }\n return;\n }\n const data = await response.json();\n const imaPayload = data.response?.ima?.[\"publisherdesk.ima\"]?.payload;\n if (imaPayload) {\n this.apiVastTagUrl = decodeURIComponent(imaPayload);\n if (this.config.debugAdTiming) {\n console.log(\n \"[StormcloudVideoPlayer] Extracted VAST tag URL from /ads/web:\",\n this.apiVastTagUrl\n );\n }\n } else {\n if (this.config.debugAdTiming) {\n console.warn(\n \"[StormcloudVideoPlayer] No VAST tag URL found in /ads/web response\"\n );\n }\n }\n const numberAds = data.response?.options?.vast?.cue_tones?.number_ads;\n if (numberAds != null && numberAds > 0) {\n this.apiNumberAds = numberAds;\n if (this.config.debugAdTiming) {\n console.log(\n \"[StormcloudVideoPlayer] Number of ads per break from API:\",\n this.apiNumberAds\n );\n }\n }\n }\n async fetchAndParseVmap(vmapUrl) {\n if (!vmapUrl.trim()) {\n return;\n }\n try {\n const response = await fetch(vmapUrl);\n if (!response.ok) {\n throw new Error(`Failed to fetch VMAP (${response.status})`);\n }\n const vmapXml = await response.text();\n this.vmapBreaks = this.parseVmapToBreaks(vmapXml);\n this.consumedVmapBreakIds.clear();\n if (this.config.debugAdTiming) {\n console.log(\n `[StormcloudVideoPlayer] Loaded ${this.vmapBreaks.length} VMAP ad break(s) from:`,\n vmapUrl\n );\n }\n } catch (error) {\n this.vmapBreaks = [];\n this.consumedVmapBreakIds.clear();\n if (this.config.debugAdTiming) {\n console.warn(\"[StormcloudVideoPlayer] Failed to load VMAP:\", error);\n }\n }\n }\n parseVmapToBreaks(vmapXml) {\n if (typeof DOMParser === \"undefined\") {\n return [];\n }\n const doc = new DOMParser().parseFromString(vmapXml, \"application/xml\");\n if (doc.querySelector(\"parsererror\")) {\n if (this.config.debugAdTiming) {\n console.warn(\"[StormcloudVideoPlayer] Invalid VMAP XML received\");\n }\n return [];\n }\n const adBreakNodes = Array.from(\n doc.querySelectorAll(\"AdBreak, vmap\\\\:AdBreak\")\n );\n const parsed = [];\n adBreakNodes.forEach((node, index) => {\n const timeOffsetRaw = (node.getAttribute(\"timeOffset\") || \"\").trim();\n const startTimeMs = this.parseVmapTimeOffsetToMs(timeOffsetRaw);\n if (startTimeMs == null) {\n return;\n }\n const adTagNode = node.querySelector(\"AdTagURI, vmap\\\\:AdTagURI\");\n const adTagUrl = (adTagNode?.textContent || \"\").trim();\n if (!adTagUrl) {\n return;\n }\n const breakId = node.getAttribute(\"breakId\") || `vmap-break-${index}-${timeOffsetRaw || \"unknown\"}`;\n parsed.push({\n id: breakId,\n startTimeMs,\n vastTagUrl: adTagUrl\n });\n });\n parsed.sort((a, b) => {\n const aStart = a.startTimeMs < 0 ? Number.MAX_SAFE_INTEGER : a.startTimeMs;\n const bStart = b.startTimeMs < 0 ? Number.MAX_SAFE_INTEGER : b.startTimeMs;\n return aStart - bStart;\n });\n return parsed;\n }\n parseVmapTimeOffsetToMs(timeOffset) {\n if (!timeOffset) {\n return void 0;\n }\n const normalized = timeOffset.trim().toLowerCase();\n if (normalized === \"start\") {\n return 0;\n }\n if (normalized === \"end\") {\n return -1;\n }\n const hms = timeOffset.match(\n /^(\\d{1,2}):(\\d{2}):(\\d{2})(?:\\.(\\d{1,3}))?$/\n );\n if (hms) {\n const [, hh, mm, ss, ms = \"0\"] = hms;\n const hours = Number(hh);\n const minutes = Number(mm);\n const seconds = Number(ss);\n const millis = Number(ms.padEnd(3, \"0\").slice(0, 3));\n return (hours * 3600 + minutes * 60 + seconds) * 1e3 + millis;\n }\n const percent = timeOffset.match(/^(\\d+(?:\\.\\d+)?)%$/);\n if (percent) {\n const ratio = Number(percent[1]) / 100;\n const durationSec = this.video.duration;\n if (Number.isFinite(durationSec) && durationSec > 0) {\n return Math.floor(durationSec * 1e3 * ratio);\n }\n return void 0;\n }\n return void 0;\n }\n getAdBreakKey(adBreak) {\n if (adBreak.id) {\n return adBreak.id;\n }\n return `${adBreak.startTimeMs}-${adBreak.vastTagUrl || \"\"}`;\n }\n resolveBreakStartMs(adBreak) {\n if (adBreak.startTimeMs >= 0) {\n return adBreak.startTimeMs;\n }\n if (adBreak.startTimeMs === -1) {\n const durationSec = this.video.duration;\n if (Number.isFinite(durationSec) && durationSec > 0) {\n return Math.floor(durationSec * 1e3);\n }\n }\n return void 0;\n }\n getCurrentAdIndex() {\n return this.currentAdIndex;\n }\n getTotalAdsInBreak() {\n return this.totalAdsInBreak;\n }\n getAdRemainingMs() {\n return this.getRemainingAdMs();\n }\n generateVastUrlsWithCorrelators(baseUrl, count) {\n const urls = [];\n const baseTimestamp = Date.now();\n for (let i = 0; i < count; i++) {\n const timestamp = baseTimestamp + i;\n const random = Math.floor(Math.random() * 1e12);\n const uniqueCorrelator = `${timestamp}_${random}_${i}`;\n let urlWithCorrelator;\n const correlatorRegex = /([?&])correlator=([^&]*)/;\n if (correlatorRegex.test(baseUrl)) {\n urlWithCorrelator = baseUrl.replace(correlatorRegex, `$1correlator=${uniqueCorrelator}`);\n } else if (baseUrl.includes(\"?\")) {\n urlWithCorrelator = `${baseUrl}&correlator=${uniqueCorrelator}`;\n } else {\n urlWithCorrelator = `${baseUrl}?correlator=${uniqueCorrelator}`;\n }\n urls.push(this.palNonce.injectNonce(urlWithCorrelator));\n }\n return urls;\n }\n isAdPlaying() {\n return this.inAdBreak && this.adPlayer.isAdPlaying();\n }\n isShowingAds() {\n return this.showAds;\n }\n getStreamType() {\n const url = this.config.src.toLowerCase();\n if (url.includes(\".m3u8\") || url.includes(\"/hls/\") || url.includes(\"application/vnd.apple.mpegurl\")) {\n return \"hls\";\n }\n return \"other\";\n }\n shouldShowNativeControls() {\n const streamType = this.getStreamType();\n if (streamType === \"other\") {\n return !(this.config.showCustomControls ?? false);\n }\n return !!(this.config.allowNativeHls && !(this.config.showCustomControls ?? false));\n }\n shouldContinueLiveStreamDuringAds() {\n if (this.config.allowNativeHls) {\n return false;\n }\n if (!this.isLiveStream) {\n return false;\n }\n return true;\n }\n startAdPrefetch(marker, fragmentSn, cueKey) {\n if (this.pendingAdBreak || this.inAdBreak) {\n return;\n }\n const scheduled = this.findCurrentOrNextBreak(this.video.currentTime * 1e3);\n const tags = this.selectVastTagsForBreak(scheduled);\n let baseVastUrl;\n if (tags && tags.length > 0 && tags[0]) {\n baseVastUrl = tags[0];\n } else if (this.apiVastTagUrl) {\n baseVastUrl = this.apiVastTagUrl;\n } else {\n if (this.config.debugAdTiming) {\n console.warn(\"[StormcloudVideoPlayer] No VAST URL available for prefetch\");\n }\n return;\n }\n const urlsToPregenerate = 5;\n const generatedUrls = this.generateVastUrlsWithCorrelators(baseVastUrl, urlsToPregenerate);\n this.pendingAdBreak = {\n marker,\n ...fragmentSn !== void 0 ? { detectedAtFragmentSn: fragmentSn } : {},\n vastUrls: generatedUrls,\n isFetching: false,\n fetchStartTime: Date.now()\n };\n this.pendingScte35CueKey = cueKey;\n this.adDetectSentForCurrentBreak = true;\n const detectPayload = {};\n if (marker.durationSeconds != null) detectPayload.durationSeconds = marker.durationSeconds;\n if (marker.ptsSeconds != null) detectPayload.ptsSeconds = marker.ptsSeconds;\n if (fragmentSn !== void 0) detectPayload.detectedAtFragmentSn = fragmentSn;\n sendAdDetectTracking(this.config.licenseKey, { source: \"scte35\", timestamp: (/* @__PURE__ */ new Date()).toISOString(), ...detectPayload }).catch(() => {\n });\n if (this.config.debugAdTiming) {\n console.log(\"[PREFETCH] \\u{1F504} Starting ad prefetch for upcoming ad break\");\n console.log(`[PREFETCH] \\u{1F4CB} Pre-generated ${generatedUrls.length} VAST URLs`);\n }\n this.startPreloadPool(baseVastUrl, generatedUrls.slice(0, this.maxPreloadPoolSize));\n }\n clearPendingAdBreak() {\n if (this.prefetchTimerId != null) {\n clearTimeout(this.prefetchTimerId);\n this.prefetchTimerId = void 0;\n }\n this.pendingAdBreak = null;\n this.pendingScte35CueKey = void 0;\n }\n startPreloadPool(baseVastUrl, initialUrls) {\n if (this.preloadPoolActive) {\n if (this.config.debugAdTiming) {\n console.log(\"[PRELOAD-POOL] Already active, skipping duplicate start\");\n }\n return;\n }\n this.preloadPoolActive = true;\n if (this.config.debugAdTiming) {\n console.log(`[PRELOAD-POOL] \\u{1F3CA} Starting preload pool EARLY (target size: ${this.maxPreloadPoolSize})`);\n console.log(`[PRELOAD-POOL] Ad break hasn't started yet, but preloading ads in advance`);\n }\n for (const url of initialUrls) {\n if (this.preloadPool.length < this.maxPreloadPoolSize) {\n this.preloadAdIntoPool(url);\n }\n }\n this.preloadPoolLoop(baseVastUrl);\n }\n async preloadAdIntoPool(vastUrl) {\n if (this.isGamInCooldown()) {\n if (this.config.debugAdTiming) {\n console.log(\"[CIRCUIT-BREAKER] GAM in cooldown, skipping preload\");\n }\n return;\n }\n if (this.preloadPool.some((entry) => entry.vastUrl === vastUrl) || this.failedVastUrls.has(vastUrl) || this.isUrlInCooldown(vastUrl)) {\n return;\n }\n if (this.preloadPool.length >= this.maxPreloadPoolSize) {\n return;\n }\n if (this.config.debugAdTiming) {\n console.log(`[PRELOAD-POOL] \\u{1F4E5} Preloading ad into pool: ${vastUrl}`);\n }\n const loadPromise = (async () => {\n let hasAdError = false;\n let adErrorPayload = null;\n let errorListenerCleanup = null;\n try {\n const continueLiveStreamDuringAds = this.shouldContinueLiveStreamDuringAds();\n const preloadAd = this.createAdPlayer(continueLiveStreamDuringAds);\n preloadAd.initialize();\n const errorListener = (payload) => {\n hasAdError = true;\n adErrorPayload = payload;\n };\n preloadAd.on(\"ad_error\", errorListener);\n errorListenerCleanup = () => preloadAd.off(\"ad_error\", errorListener);\n await this.enforceGlobalRateLimit();\n await preloadAd.requestAds(vastUrl);\n preloadAd.pause();\n await new Promise((resolve) => setTimeout(resolve, 1500));\n preloadAd.pause();\n if (hasAdError) {\n const isNoFill = adErrorPayload?.isNoFill || adErrorPayload?.code === 303 || adErrorPayload?.vastErrorCode === 303;\n if (errorListenerCleanup) {\n errorListenerCleanup();\n }\n preloadAd.destroy();\n this.recordGamNoFill();\n if (isNoFill) {\n if (this.config.debugAdTiming) {\n console.log(`[PRELOAD-POOL] \\u26A0\\uFE0F Ad preload returned no-fill: ${vastUrl}`);\n }\n this.temporaryFailureUrls.set(vastUrl, Date.now());\n } else {\n if (this.config.debugAdTiming) {\n console.log(`[PRELOAD-POOL] \\u26A0\\uFE0F Ad preload failed with error: ${vastUrl}`, adErrorPayload);\n }\n if (adErrorPayload && !this.isTemporaryAdError(adErrorPayload)) {\n this.failedVastUrls.add(vastUrl);\n } else {\n this.temporaryFailureUrls.set(vastUrl, Date.now());\n }\n }\n return;\n }\n const poolEntry = {\n vastUrl,\n adController: preloadAd,\n loadedAt: Date.now(),\n isReady: true,\n loadPromise: Promise.resolve()\n };\n const lateErrorListener = (payload) => {\n const index = this.preloadPool.findIndex((entry) => entry.vastUrl === vastUrl);\n if (index >= 0) {\n this.preloadPool.splice(index, 1);\n if (this.config.debugAdTiming) {\n console.log(`[PRELOAD-POOL] \\u26A0\\uFE0F Late error detected, removed from pool: ${vastUrl}`, payload);\n }\n try {\n preloadAd.destroy();\n } catch {\n }\n }\n };\n preloadAd.on(\"ad_error\", lateErrorListener);\n this.preloadPool.push(poolEntry);\n if (this.config.debugAdTiming) {\n console.log(`[PRELOAD-POOL] \\u2705 Ad preloaded (no errors detected within timeout) (pool size: ${this.preloadPool.length}/${this.maxPreloadPoolSize})`);\n }\n if (errorListenerCleanup) {\n errorListenerCleanup();\n }\n } catch (error) {\n if (errorListenerCleanup) {\n errorListenerCleanup();\n }\n this.recordGamNoFill();\n if (this.config.debugAdTiming) {\n console.warn(`[PRELOAD-POOL] \\u26A0\\uFE0F Failed to preload ad: ${vastUrl}`, error);\n }\n if (error instanceof Error && !this.isTemporaryAdError(error)) {\n this.failedVastUrls.add(vastUrl);\n } else if (error instanceof Error && this.isTemporaryAdError(error)) {\n this.temporaryFailureUrls.set(vastUrl, Date.now());\n }\n }\n })();\n loadPromise.catch(() => {\n });\n }\n async preloadPoolLoop(baseVastUrl) {\n if (this.preloadPoolLoopRunning) {\n return;\n }\n this.preloadPoolLoopRunning = true;\n if (this.config.debugAdTiming) {\n console.log(\"[PRELOAD-POOL] \\u{1F504} Starting continuous preload loop\");\n }\n while (this.preloadPoolActive) {\n if (this.isGamInCooldown()) {\n if (this.config.debugAdTiming) {\n console.log(\"[CIRCUIT-BREAKER] GAM in cooldown, stopping preload pool loop\");\n }\n break;\n }\n if (!this.inAdBreak && this.preloadPool.length >= this.maxPreloadPoolSize) {\n await new Promise((resolve) => setTimeout(resolve, 2e3));\n continue;\n }\n if (!this.inAdBreak && this.pendingAdBreak === null) {\n if (this.config.debugAdTiming) {\n console.log(\"[PRELOAD-POOL] Ad break cancelled, stopping preload pool\");\n }\n break;\n }\n while (this.preloadPool.length < this.maxPreloadPoolSize) {\n if (!this.preloadPoolActive || this.isGamInCooldown()) {\n break;\n }\n if (this.inAdBreak) {\n const remaining = this.getRemainingAdMs();\n if (remaining <= 0) {\n break;\n }\n }\n const newUrls = this.generateVastUrlsWithCorrelators(baseVastUrl, 1);\n const newUrl = newUrls[0];\n if (newUrl && !this.failedVastUrls.has(newUrl) && !this.isUrlInCooldown(newUrl)) {\n await this.preloadAdIntoPool(newUrl);\n }\n await new Promise((resolve) => setTimeout(resolve, 1e3));\n }\n await new Promise((resolve) => setTimeout(resolve, 2e3));\n }\n this.preloadPoolLoopRunning = false;\n if (this.config.debugAdTiming) {\n console.log(\"[PRELOAD-POOL] \\u{1F6D1} Preload loop ended\");\n }\n }\n getPreloadedAd() {\n if (this.preloadPool.length === 0) {\n return null;\n }\n const entry = this.preloadPool.shift();\n if (!entry || !entry.isReady) {\n return null;\n }\n if (this.config.debugAdTiming) {\n console.log(`[PRELOAD-POOL] \\u{1F3AF} Using preloaded ad from pool (${this.preloadPool.length} remaining)`);\n }\n return {\n vastUrl: entry.vastUrl,\n adController: entry.adController\n };\n }\n stopPreloadPool() {\n this.preloadPoolActive = false;\n this.preloadPoolLoopRunning = false;\n for (const entry of this.preloadPool) {\n try {\n entry.adController.destroy();\n } catch (error) {\n if (this.config.debugAdTiming) {\n console.warn(\"[PRELOAD-POOL] Error destroying preloaded controller:\", error);\n }\n }\n }\n this.preloadPool = [];\n if (this.config.debugAdTiming) {\n console.log(\"[PRELOAD-POOL] \\u{1F6D1} Preload pool stopped and cleaned up\");\n }\n }\n async handleAdStart(_marker) {\n const scheduled = this.findCurrentOrNextBreak(\n this.video.currentTime * 1e3\n );\n if (scheduled) {\n this.consumedVmapBreakIds.add(this.getAdBreakKey(scheduled));\n }\n const tags = this.selectVastTagsForBreak(scheduled);\n let baseVastUrl;\n if (tags && tags.length > 0 && tags[0]) {\n baseVastUrl = tags[0];\n } else if (this.apiVastTagUrl) {\n baseVastUrl = this.apiVastTagUrl;\n } else {\n this.clearPendingAdBreak();\n return;\n }\n const adBreakDurationMs = _marker.durationSeconds != null ? _marker.durationSeconds * 1e3 : scheduled?.durationMs;\n if (this.config.debugAdTiming) {\n const mode = this.isLiveStream ? \"LIVE\" : \"VOD\";\n console.log(\n `[CONTINUOUS-FETCH] \\u{1F4FA} ${mode} MODE: Target duration=${adBreakDurationMs}ms`\n );\n }\n this.failedVastUrls.clear();\n this.temporaryFailureUrls.clear();\n this.consecutiveFailures = 0;\n this.continuousFetchingActive = true;\n this.isShowingPlaceholder = false;\n this.totalAdRequestsInBreak = 0;\n const currentMuted = this.video.muted;\n const currentVolume = this.video.volume;\n this.adPlayer.updateOriginalMutedState(currentMuted, currentVolume);\n if (!this.video.muted) {\n this.video.muted = true;\n this.video.volume = 0;\n if (this.config.debugAdTiming) {\n console.log(\"[StormcloudVideoPlayer] Muted video in handleAdStart\");\n }\n }\n this.inAdBreak = true;\n this.currentAdBreakStartWallClockMs = Date.now();\n this.currentAdIndex = 0;\n this.totalAdsInBreak = 1;\n this.adPodQueue = [];\n this.showAds = true;\n this.showPlaceholderLayer();\n this.adPlayer.showPlaceholder();\n if (this.expectedAdBreakDurationMs == null && adBreakDurationMs != null) {\n this.expectedAdBreakDurationMs = adBreakDurationMs;\n }\n let firstAdUrl;\n let usePreloadedAd = false;\n let preloadedController;\n const preloaded = this.getPreloadedAd();\n if (preloaded) {\n firstAdUrl = preloaded.vastUrl;\n preloadedController = preloaded.adController;\n usePreloadedAd = true;\n sendAdLoadedTracking(\n this.config.licenseKey,\n { source: \"hls\", vastUrl: firstAdUrl, timestamp: (/* @__PURE__ */ new Date()).toISOString() }\n ).catch(() => {\n });\n if (this.config.debugAdTiming) {\n console.log(\"[CONTINUOUS-FETCH] \\u{1F680} Using preloaded ad from pool (preloaded in advance, ready immediately!)\");\n console.log(`[CONTINUOUS-FETCH] Pool still has ${this.preloadPool.length} preloaded ads ready`);\n }\n } else if (this.pendingAdBreak && this.pendingAdBreak.vastUrls.length > 0) {\n this.adRequestQueue = [...this.pendingAdBreak.vastUrls];\n firstAdUrl = this.adRequestQueue.shift();\n if (this.config.debugAdTiming) {\n console.log(`[CONTINUOUS-FETCH] \\u26A0\\uFE0F Pool empty, using prefetched URLs (${this.adRequestQueue.length + 1} available)`);\n }\n this.clearPendingAdBreak();\n } else {\n if (this.config.debugAdTiming) {\n console.log(\"[CONTINUOUS-FETCH] \\u{1F680} Generating new ad URLs...\");\n }\n const firstAdUrlArray = this.generateVastUrlsWithCorrelators(baseVastUrl, 1);\n firstAdUrl = firstAdUrlArray[0];\n this.adRequestQueue = [];\n }\n if (!firstAdUrl) {\n if (this.config.debugAdTiming) {\n console.warn(\"[CONTINUOUS-FETCH] \\u26A0\\uFE0F Failed to get first ad URL\");\n }\n this.handleAdPodComplete();\n return;\n }\n if (this.config.debugAdTiming) {\n console.log(\"[CONTINUOUS-FETCH] \\u{1F4CB} First VAST URL:\", firstAdUrl);\n }\n try {\n if (usePreloadedAd && preloadedController) {\n this.adPlayer.destroy();\n this.video.muted = true;\n this.video.volume = 0;\n this.adPlayer = preloadedController;\n this.attachImaEventListeners();\n if (this.config.debugAdTiming) {\n console.log(\"[CONTINUOUS-FETCH] \\u2705 Using preloaded ad, resuming and starting playback immediately (no request delay!)\");\n }\n this.adPlayer.resume();\n this.consecutiveFailures = 0;\n this.currentAdIndex++;\n this.startContinuousFetching(baseVastUrl);\n if (!this.preloadPoolActive) {\n this.preloadPoolActive = true;\n this.preloadPoolLoop(baseVastUrl);\n }\n await this.adPlayer.play();\n if (this.expectedAdBreakDurationMs != null && this.adStopTimerId == null) {\n this.scheduleAdStopCountdown(this.getRemainingAdMs());\n }\n const adVolume = currentMuted ? 0 : currentVolume;\n this.adPlayer.setAdVolume(adVolume);\n } else {\n await this.enforceGlobalRateLimit();\n this.lastAdRequestTime = Date.now();\n await this.adPlayer.requestAds(firstAdUrl);\n sendAdLoadedTracking(\n this.config.licenseKey,\n { source: \"hls\", vastUrl: firstAdUrl, timestamp: (/* @__PURE__ */ new Date()).toISOString() }\n ).catch(() => {\n });\n if (this.config.debugAdTiming) {\n console.log(\"[CONTINUOUS-FETCH] \\u2705 First ad request successful, starting playback\");\n }\n this.consecutiveFailures = 0;\n this.currentAdIndex++;\n this.startContinuousFetching(baseVastUrl);\n if (!this.preloadPoolActive) {\n this.startPreloadPool(baseVastUrl, []);\n }\n await this.adPlayer.play();\n if (this.expectedAdBreakDurationMs != null && this.adStopTimerId == null) {\n this.scheduleAdStopCountdown(this.getRemainingAdMs());\n }\n const adVolume = currentMuted ? 0 : currentVolume;\n this.adPlayer.setAdVolume(adVolume);\n }\n } catch (error) {\n if (this.config.debugAdTiming) {\n console.warn(\"[CONTINUOUS-FETCH] \\u26A0\\uFE0F First ad request failed:\", error);\n }\n if (!usePreloadedAd) {\n const fallbackPreloaded = this.getPreloadedAd();\n if (fallbackPreloaded) {\n if (this.config.debugAdTiming) {\n console.log(\"[CONTINUOUS-FETCH] \\u{1F504} First ad failed, using preloaded fallback\");\n }\n try {\n this.adPlayer.destroy();\n this.video.muted = true;\n this.video.volume = 0;\n this.adPlayer = fallbackPreloaded.adController;\n this.attachImaEventListeners();\n this.adPlayer.resume();\n this.consecutiveFailures = 0;\n this.currentAdIndex++;\n this.startContinuousFetching(baseVastUrl);\n if (!this.preloadPoolActive) {\n this.preloadPoolActive = true;\n this.preloadPoolLoop(baseVastUrl);\n }\n await this.adPlayer.play();\n if (this.expectedAdBreakDurationMs != null && this.adStopTimerId == null) {\n this.scheduleAdStopCountdown(this.getRemainingAdMs());\n }\n const adVolume = currentMuted ? 0 : currentVolume;\n this.adPlayer.setAdVolume(adVolume);\n return;\n } catch (fallbackError) {\n if (this.config.debugAdTiming) {\n console.warn(\"[CONTINUOUS-FETCH] \\u26A0\\uFE0F Preloaded fallback also failed:\", fallbackError);\n }\n }\n }\n }\n if (this.isTemporaryAdError(error)) {\n this.temporaryFailureUrls.set(firstAdUrl, Date.now());\n if (this.config.debugAdTiming) {\n console.log(\"[CONTINUOUS-FETCH] First ad had temporary error (no-fill) - will try alternatives\");\n }\n } else {\n this.failedVastUrls.add(firstAdUrl);\n if (this.config.debugAdTiming) {\n console.log(\"[CONTINUOUS-FETCH] First ad had permanent error - URL blacklisted\");\n }\n }\n this.consecutiveFailures++;\n this.startContinuousFetching(baseVastUrl);\n await this.tryNextAvailableAdWithRateLimit();\n }\n }\n startContinuousFetching(baseVastUrl) {\n if (!this.continuousFetchingActive) {\n return;\n }\n if (this.continuousFetchLoopRunning) {\n if (this.config.debugAdTiming) {\n console.log(\"[CONTINUOUS-FETCH] \\u23ED\\uFE0F Fetch loop already running, skipping duplicate start\");\n }\n return;\n }\n if (this.config.debugAdTiming) {\n console.log(\"[CONTINUOUS-FETCH] \\u{1F504} Starting continuous ad fetching loop\");\n }\n this.continuousFetchLoopRunning = true;\n this.continuousFetchLoop(baseVastUrl);\n }\n async continuousFetchLoop(baseVastUrl) {\n while (this.continuousFetchingActive && this.inAdBreak) {\n const remaining = this.getRemainingAdMs();\n if (remaining <= 0) {\n if (this.config.debugAdTiming) {\n console.log(\"[CONTINUOUS-FETCH] \\u23F9\\uFE0F Ad break time expired, stopping URL generation\");\n }\n break;\n }\n if (this.isGamInCooldown()) {\n if (this.config.debugAdTiming) {\n console.log(\"[CIRCUIT-BREAKER] GAM in cooldown, stopping URL generation\");\n }\n break;\n }\n if (this.consecutiveFailures >= this.maxConsecutiveFailures) {\n if (this.config.debugAdTiming) {\n console.log(`[CONTINUOUS-FETCH] \\u{1F6D1} Too many consecutive failures (${this.consecutiveFailures}), stopping URL generation`);\n }\n break;\n }\n if (this.totalAdRequestsInBreak >= this.maxTotalAdRequestsPerBreak) {\n if (this.config.debugAdTiming) {\n console.log(`[CONTINUOUS-FETCH] \\u{1F6D1} Maximum ad requests reached (${this.maxTotalAdRequestsPerBreak}), stopping`);\n }\n break;\n }\n const maxQueueSize = 5;\n if (this.adRequestQueue.length >= maxQueueSize) {\n if (this.config.debugAdTiming) {\n console.log(`[CONTINUOUS-FETCH] \\u23F8\\uFE0F URL queue full (${this.adRequestQueue.length}), waiting...`);\n }\n await new Promise((resolve) => setTimeout(resolve, 1e3));\n continue;\n }\n const newAdUrl = this.generateVastUrlsWithCorrelators(baseVastUrl, 1)[0];\n if (!newAdUrl || this.failedVastUrls.has(newAdUrl) || this.isUrlInCooldown(newAdUrl)) {\n await new Promise((resolve) => setTimeout(resolve, 500));\n continue;\n }\n if (this.config.debugAdTiming) {\n const queuedUrlsPreview = [...this.adRequestQueue, newAdUrl];\n console.log(\n `[CONTINUOUS-FETCH] \\u{1F4DD} Queued VAST URL (queue size: ${queuedUrlsPreview.length})`,\n { queuedUrls: queuedUrlsPreview }\n );\n }\n this.adRequestQueue.push(newAdUrl);\n this.totalAdsInBreak++;\n const generationDelay = this.consecutiveFailures > 0 ? Math.min(1e3 * Math.pow(2, this.consecutiveFailures), 5e3) : 500;\n await new Promise((resolve) => setTimeout(resolve, generationDelay));\n }\n this.continuousFetchLoopRunning = false;\n if (this.config.debugAdTiming) {\n console.log(\n `[CONTINUOUS-FETCH] \\u{1F6D1} URL generation loop ended (queued: ${this.adRequestQueue.length})`,\n this.adRequestQueue.length > 0 ? { queuedUrls: [...this.adRequestQueue] } : {}\n );\n }\n }\n stopContinuousFetching() {\n this.continuousFetchingActive = false;\n this.continuousFetchLoopRunning = false;\n this.hidePlaceholderLayer();\n if (this.config.debugAdTiming) {\n console.log(\"[CONTINUOUS-FETCH] \\u{1F6D1} Stopping continuous ad fetching\");\n }\n }\n async tryNextAvailableAdWithRateLimit() {\n if (this.consecutiveFailures >= this.maxConsecutiveFailures) {\n if (this.config.debugAdTiming) {\n console.log(`[CONTINUOUS-FETCH] \\u{1F6D1} Too many consecutive failures (${this.consecutiveFailures}), ending ad break gracefully`);\n }\n this.handleAdPodComplete();\n return;\n }\n const backoffMultiplier = Math.pow(2, this.consecutiveFailures);\n const backoffDelay = Math.min(this.backoffBaseMs * backoffMultiplier, this.maxBackoffMs);\n const effectiveMinInterval = this.minAdRequestIntervalMs + (this.consecutiveFailures > 0 ? backoffDelay : 0);\n const timeSinceLastRequest = Date.now() - this.lastAdRequestTime;\n if (timeSinceLastRequest < effectiveMinInterval) {\n const waitTime = effectiveMinInterval - timeSinceLastRequest;\n if (this.config.debugAdTiming) {\n console.log(`[CONTINUOUS-FETCH] \\u23F3 Rate limiting: waiting ${waitTime}ms before next request (backoff: ${this.consecutiveFailures} failures)`);\n }\n await new Promise((resolve) => setTimeout(resolve, waitTime));\n }\n return this.tryNextAvailableAd(0);\n }\n async tryNextAvailableAd(retryCount = 0) {\n const remaining = this.getRemainingAdMs();\n if (remaining <= 500) {\n if (this.config.debugAdTiming) {\n console.log(\"[CONTINUOUS-FETCH] \\u23F9\\uFE0F No time remaining, ending ad break\");\n }\n this.handleAdPodComplete();\n return;\n }\n if (this.isGamInCooldown()) {\n if (this.config.debugAdTiming) {\n console.log(\"[CIRCUIT-BREAKER] GAM in cooldown, ending ad break gracefully\");\n }\n this.handleAdPodComplete();\n return;\n }\n if (this.consecutiveFailures >= this.maxConsecutiveFailures) {\n if (this.config.debugAdTiming) {\n console.log(`[CONTINUOUS-FETCH] \\u{1F6D1} Too many consecutive failures (${this.consecutiveFailures}), ending ad break`);\n }\n this.handleAdPodComplete();\n return;\n }\n this.cleanupTemporaryFailures();\n const preloaded = this.getPreloadedAd();\n if (preloaded) {\n if (this.config.debugAdTiming) {\n console.log(`[CONTINUOUS-FETCH] \\u{1F3AF} Using preloaded ad from pool (${this.preloadPool.length} remaining in pool)`);\n }\n sendAdLoadedTracking(\n this.config.licenseKey,\n { source: \"hls\", vastUrl: preloaded.vastUrl, timestamp: (/* @__PURE__ */ new Date()).toISOString() }\n ).catch(() => {\n });\n try {\n this.adPlayer.destroy();\n this.video.muted = true;\n this.video.volume = 0;\n this.adPlayer = preloaded.adController;\n this.attachImaEventListeners();\n this.adPlayer.resume();\n this.currentAdIndex++;\n this.totalAdRequestsInBreak++;\n this.lastAdRequestTime = Date.now();\n await this.adPlayer.play();\n if (this.expectedAdBreakDurationMs != null && this.adStopTimerId == null) {\n this.scheduleAdStopCountdown(this.getRemainingAdMs());\n }\n const currentMuted = this.video.muted;\n const currentVolume = this.video.volume;\n const adVolume = currentMuted ? 0 : currentVolume;\n this.adPlayer.setAdVolume(adVolume);\n this.consecutiveFailures = 0;\n return;\n } catch (error) {\n if (this.config.debugAdTiming) {\n console.warn(\"[CONTINUOUS-FETCH] \\u26A0\\uFE0F Preloaded ad failed to play:\", error);\n }\n }\n }\n while (this.adRequestQueue.length > 0) {\n const nextAdUrl = this.adRequestQueue.shift();\n if (!nextAdUrl) {\n continue;\n }\n if (this.failedVastUrls.has(nextAdUrl)) {\n if (this.config.debugAdTiming) {\n console.log(\"[CONTINUOUS-FETCH] \\u23ED\\uFE0F Skipping permanently-failed URL, trying next...\");\n }\n continue;\n }\n if (this.isUrlInCooldown(nextAdUrl)) {\n if (this.config.debugAdTiming) {\n console.log(\"[CONTINUOUS-FETCH] \\u23ED\\uFE0F Skipping URL in cooldown (recent no-fill), trying next...\");\n }\n continue;\n }\n if (this.config.debugAdTiming) {\n console.log(`[CONTINUOUS-FETCH] \\u{1F3AC} Requesting next ad via HLS ad player (${this.currentAdIndex + 1}/${this.totalAdsInBreak}, ${this.adRequestQueue.length} remaining in queue)`);\n }\n const currentMuted = this.video.muted;\n const currentVolume = this.video.volume;\n this.adPlayer.updateOriginalMutedState(currentMuted, currentVolume);\n this.currentAdIndex++;\n this.totalAdRequestsInBreak++;\n this.lastAdRequestTime = Date.now();\n try {\n await this.playSingleAd(nextAdUrl);\n this.consecutiveFailures = 0;\n } catch (error) {\n const errorMessage = error.message;\n if (this.config.debugAdTiming) {\n console.log(\"[CONTINUOUS-FETCH] \\u274C Ad request failed:\", errorMessage);\n }\n if (!errorMessage.includes(\"permanently failed\") && !errorMessage.includes(\"in cooldown\")) {\n this.consecutiveFailures++;\n }\n await this.tryNextAvailableAdWithRateLimit();\n }\n return;\n }\n const maxRetries = 3;\n if (this.continuousFetchingActive && retryCount < maxRetries && remaining > 2e3) {\n if (this.config.debugAdTiming) {\n console.log(`[CONTINUOUS-FETCH] \\u23F3 Queue empty, waiting for URLs... (${retryCount + 1}/${maxRetries})`);\n }\n await new Promise((resolve) => setTimeout(resolve, 500));\n await this.tryNextAvailableAd(retryCount + 1);\n return;\n }\n if (!this.isShowingPlaceholder && remaining > 1e3) {\n this.showPlaceholderAndWaitForAds();\n } else {\n if (this.config.debugAdTiming) {\n console.log(\"[CONTINUOUS-FETCH] \\u23F9\\uFE0F No more ads available, ending ad break\");\n }\n this.handleAdPodComplete();\n }\n }\n async showPlaceholderAndWaitForAds() {\n const remaining = this.getRemainingAdMs();\n const waitTime = Math.min(this.maxPlaceholderDurationMs, remaining);\n if (this.isGamInCooldown()) {\n if (this.config.debugAdTiming) {\n console.log(\"[CIRCUIT-BREAKER] GAM in cooldown, skipping placeholder wait\");\n }\n this.handleAdPodComplete();\n return;\n }\n if (this.consecutiveFailures >= this.maxConsecutiveFailures) {\n if (this.config.debugAdTiming) {\n console.log(\"[CONTINUOUS-FETCH] \\u{1F6D1} Skipping placeholder - too many consecutive failures\");\n }\n this.handleAdPodComplete();\n return;\n }\n if (waitTime < 1e3) {\n this.handleAdPodComplete();\n return;\n }\n if (this.config.debugAdTiming) {\n console.log(`[CONTINUOUS-FETCH] \\u2B1B Showing placeholder for ${waitTime}ms while waiting for ad URLs`);\n }\n this.isShowingPlaceholder = true;\n this.adPlayer.showPlaceholder();\n const checkInterval = 300;\n const maxChecks = Math.floor(waitTime / checkInterval);\n for (let i = 0; i < maxChecks; i++) {\n await new Promise((resolve) => setTimeout(resolve, checkInterval));\n if (!this.inAdBreak) {\n return;\n }\n if (this.consecutiveFailures >= this.maxConsecutiveFailures) {\n if (this.config.debugAdTiming) {\n console.log(\"[CONTINUOUS-FETCH] \\u{1F6D1} Too many failures during placeholder wait\");\n }\n break;\n }\n while (this.adRequestQueue.length > 0) {\n const nextAdUrl = this.adRequestQueue.shift();\n if (!nextAdUrl) {\n continue;\n }\n if (this.failedVastUrls.has(nextAdUrl)) {\n continue;\n }\n if (this.isUrlInCooldown(nextAdUrl)) {\n continue;\n }\n if (this.config.debugAdTiming) {\n console.log(\"[CONTINUOUS-FETCH] \\u2705 Ad URL available, requesting via HLS ad player\");\n }\n this.isShowingPlaceholder = false;\n this.adPlayer.hidePlaceholder();\n const currentMuted = this.video.muted;\n const currentVolume = this.video.volume;\n this.adPlayer.updateOriginalMutedState(currentMuted, currentVolume);\n this.currentAdIndex++;\n this.totalAdRequestsInBreak++;\n this.lastAdRequestTime = Date.now();\n try {\n await this.playSingleAd(nextAdUrl);\n this.consecutiveFailures = 0;\n } catch (error) {\n const errorMessage = error.message;\n if (!errorMessage.includes(\"permanently failed\") && !errorMessage.includes(\"in cooldown\")) {\n this.consecutiveFailures++;\n }\n await this.tryNextAvailableAdWithRateLimit();\n }\n return;\n }\n }\n if (this.config.debugAdTiming) {\n console.log(\"[CONTINUOUS-FETCH] \\u23F0 Placeholder timeout, ending ad break\");\n }\n this.isShowingPlaceholder = false;\n this.adPlayer.hidePlaceholder();\n this.handleAdPodComplete();\n }\n findCurrentOrNextBreak(nowMs) {\n const schedule = this.vmapBreaks;\n let candidate;\n for (const b of schedule) {\n if (this.consumedVmapBreakIds.has(this.getAdBreakKey(b))) {\n continue;\n }\n const breakStartMs = this.resolveBreakStartMs(b);\n if (breakStartMs == null) {\n continue;\n }\n const tol = this.config.driftToleranceMs ?? 1e3;\n if (breakStartMs <= nowMs + tol && (candidate == null || breakStartMs > (this.resolveBreakStartMs(candidate) ?? 0))) {\n candidate = b;\n }\n }\n return candidate;\n }\n onTimeUpdate(currentTimeSec) {\n if (this.adPlayer.isAdPlaying() || this.inAdBreak) return;\n const nowMs = currentTimeSec * 1e3;\n const breakToPlay = this.findBreakForTime(nowMs);\n if (breakToPlay) {\n void this.handleMidAdJoin(breakToPlay, nowMs).catch((error) => {\n if (this.config.debugAdTiming) {\n console.warn(\n \"[StormcloudVideoPlayer] Mid-roll VMAP join failed gracefully:\",\n error\n );\n }\n });\n }\n }\n async handleMidAdJoin(adBreak, nowMs) {\n const key = this.getAdBreakKey(adBreak);\n if (this.consumedVmapBreakIds.has(key)) {\n return;\n }\n const breakStartMs = this.resolveBreakStartMs(adBreak);\n if (breakStartMs == null) {\n return;\n }\n const durationMs = adBreak.durationMs ?? 0;\n const endMs = breakStartMs + durationMs;\n const tol = this.config.driftToleranceMs ?? 1e3;\n const inWindow = durationMs > 0 ? nowMs > breakStartMs && nowMs < endMs : nowMs + tol >= breakStartMs;\n if (inWindow) {\n this.consumedVmapBreakIds.add(key);\n const remainingMs = durationMs > 0 ? Math.max(0, endMs - nowMs) : 0;\n const tags = this.selectVastTagsForBreak(adBreak) || (this.apiVastTagUrl ? [this.apiVastTagUrl] : void 0);\n if (tags && tags.length > 0) {\n const first = tags[0];\n const rest = tags.slice(1);\n this.adPodQueue = rest;\n this.adPlayer.updateOriginalMutedState(this.video.muted, this.video.volume);\n try {\n await this.playSingleAd(first);\n this.inAdBreak = true;\n this.expectedAdBreakDurationMs = remainingMs;\n this.currentAdBreakStartWallClockMs = Date.now();\n this.scheduleAdStopCountdown(remainingMs);\n } catch (error) {\n this.adPodQueue = [];\n if (this.config.debugAdTiming) {\n console.warn(\n \"[StormcloudVideoPlayer] Mid-roll VMAP ad request failed:\",\n error\n );\n }\n }\n }\n }\n }\n scheduleAdStopCountdown(remainingMs) {\n this.clearAdStopTimer();\n const ms = Math.max(0, Math.floor(remainingMs));\n if (ms === 0) {\n this.ensureAdStoppedByTimer();\n return;\n }\n this.adStopTimerId = window.setTimeout(() => {\n this.ensureAdStoppedByTimer();\n }, ms);\n }\n clearAdStopTimer() {\n if (this.adStopTimerId != null) {\n clearTimeout(this.adStopTimerId);\n this.adStopTimerId = void 0;\n }\n }\n ensureAdStoppedByTimer() {\n if (!this.inAdBreak) return;\n this.adStopTimerId = void 0;\n const adPlaying = this.adPlayer.isAdPlaying();\n const pendingAds = this.adPodQueue.length > 0;\n const checkIntervalMs = Math.max(\n 250,\n Math.floor(this.config.adBreakCheckIntervalMs ?? 1e3)\n );\n const maxExtensionMsConfig = this.config.maxAdBreakExtensionMs;\n const maxExtensionMs = typeof maxExtensionMsConfig === \"number\" && maxExtensionMsConfig > 0 ? maxExtensionMsConfig : 6e4;\n let elapsedSinceStartMs = 0;\n if (this.currentAdBreakStartWallClockMs != null) {\n elapsedSinceStartMs = Date.now() - this.currentAdBreakStartWallClockMs;\n }\n const expectedDurationMs = this.expectedAdBreakDurationMs ?? 0;\n const overrunMs = Math.max(0, elapsedSinceStartMs - expectedDurationMs);\n const shouldExtendAdBreak = (adPlaying || pendingAds || this.showAds) && overrunMs < maxExtensionMs;\n if (shouldExtendAdBreak) {\n this.scheduleAdStopCountdown(checkIntervalMs);\n return;\n }\n if (adPlaying) {\n this.adPlayer.stop().catch(() => {\n });\n }\n this.handleAdPodComplete();\n }\n scheduleAdStartIn(delayMs, marker = { type: \"start\" }, cueKey) {\n this.clearAdStartTimer();\n const ms = Math.max(0, Math.floor(delayMs));\n if (ms === 0) {\n this.startScte35AdBreak(\n marker,\n cueKey,\n marker.durationSeconds != null ? marker.durationSeconds * 1e3 : void 0\n );\n return;\n }\n this.adStartTimerId = window.setTimeout(() => {\n this.startScte35AdBreak(\n marker,\n cueKey,\n marker.durationSeconds != null ? marker.durationSeconds * 1e3 : this.expectedAdBreakDurationMs\n );\n }, ms);\n }\n clearAdStartTimer() {\n if (this.adStartTimerId != null) {\n clearTimeout(this.adStartTimerId);\n this.adStartTimerId = void 0;\n }\n }\n updatePtsDrift(ptsSecondsSample) {\n const sampleMs = (this.video.currentTime - ptsSecondsSample) * 1e3;\n if (!Number.isFinite(sampleMs) || Math.abs(sampleMs) > 6e4) return;\n const alpha = 0.1;\n this.ptsDriftEmaMs = this.ptsDriftEmaMs * (1 - alpha) + sampleMs * alpha;\n }\n isTemporaryAdError(error) {\n const message = error?.message?.toLowerCase() || \"\";\n if (message.includes(\"no ads available\") || message.includes(\"no fill\") || message.includes(\"nofill\")) {\n return true;\n }\n if (message.includes(\"timeout\")) {\n return true;\n }\n if (message.includes(\"rate limit\") || message.includes(\"too many requests\")) {\n return true;\n }\n if (message.includes(\"ad playback error\")) {\n return true;\n }\n return false;\n }\n isUrlInCooldown(vastTagUrl) {\n const failureTime = this.temporaryFailureUrls.get(vastTagUrl);\n if (failureTime == null) {\n return false;\n }\n const elapsed = Date.now() - failureTime;\n if (elapsed >= this.temporaryFailureCooldownMs) {\n this.temporaryFailureUrls.delete(vastTagUrl);\n return false;\n }\n return true;\n }\n cleanupTemporaryFailures() {\n const now = Date.now();\n for (const [url, timestamp] of this.temporaryFailureUrls) {\n if (now - timestamp >= this.temporaryFailureCooldownMs) {\n this.temporaryFailureUrls.delete(url);\n }\n }\n }\n isGamInCooldown() {\n return Date.now() < this.globalNoFillCooldownUntil;\n }\n recordGamNoFill() {\n this.globalConsecutiveNoFills++;\n if (this.globalConsecutiveNoFills >= this.globalNoFillThreshold) {\n const exponent = this.globalConsecutiveNoFills - this.globalNoFillThreshold;\n const backoff = Math.min(\n this.globalNoFillBackoffBaseMs * Math.pow(2, exponent),\n this.globalNoFillBackoffMaxMs\n );\n this.globalNoFillCooldownUntil = Date.now() + backoff;\n if (this.config.debugAdTiming) {\n console.log(\n `[CIRCUIT-BREAKER] GAM cooldown activated: ${backoff}ms (${this.globalConsecutiveNoFills} consecutive no-fills)`\n );\n }\n }\n }\n resetGamNoFillCounter() {\n if (this.globalConsecutiveNoFills > 0 && this.config.debugAdTiming) {\n console.log(\n `[CIRCUIT-BREAKER] Resetting no-fill counter (was ${this.globalConsecutiveNoFills})`\n );\n }\n this.globalConsecutiveNoFills = 0;\n this.globalNoFillCooldownUntil = 0;\n }\n async enforceGlobalRateLimit() {\n const now = Date.now();\n const elapsed = now - this.globalLastGamRequestTime;\n if (elapsed < this.globalMinGamIntervalMs) {\n const waitMs = this.globalMinGamIntervalMs - elapsed;\n if (this.config.debugAdTiming) {\n console.log(`[RATE-LIMIT] Waiting ${waitMs}ms before next GAM request`);\n }\n await new Promise((resolve) => setTimeout(resolve, waitMs));\n }\n this.globalLastGamRequestTime = Date.now();\n }\n async playSingleAd(vastTagUrl) {\n if (this.adPlayer.isAdPlaying()) {\n return;\n }\n if (this.failedVastUrls.has(vastTagUrl)) {\n if (this.config.debugAdTiming) {\n console.warn(\"[AD-ERROR] Skipping permanently-failed VAST URL:\", vastTagUrl);\n }\n throw new Error(\"VAST URL permanently failed\");\n }\n if (this.isUrlInCooldown(vastTagUrl)) {\n if (this.config.debugAdTiming) {\n console.warn(\"[AD-ERROR] Skipping URL in cooldown (recent no-fill):\", vastTagUrl);\n }\n throw new Error(\"VAST URL in cooldown after no-fill\");\n }\n if (this.consecutiveFailures >= this.maxConsecutiveFailures) {\n if (this.config.debugAdTiming) {\n console.warn(\"[AD-ERROR] Too many consecutive failures, not requesting more ads\");\n }\n throw new Error(\"Too many consecutive failures\");\n }\n if (this.isGamInCooldown()) {\n if (this.config.debugAdTiming) {\n console.warn(\"[CIRCUIT-BREAKER] GAM in cooldown, skipping ad request\");\n }\n throw new Error(\"GAM in cooldown\");\n }\n this.recreateAdController();\n const requestToken = ++this.adRequestTokenCounter;\n this.activeAdRequestToken = requestToken;\n this.startAdRequestWatchdog(requestToken);\n try {\n await this.enforceGlobalRateLimit();\n this.lastAdRequestTime = Date.now();\n await this.adPlayer.requestAds(vastTagUrl);\n sendAdLoadedTracking(\n this.config.licenseKey,\n { source: \"hls\", vastUrl: vastTagUrl, timestamp: (/* @__PURE__ */ new Date()).toISOString() }\n ).catch(() => {\n });\n this.clearAdRequestWatchdog();\n if (this.activeAdRequestToken !== requestToken) {\n return;\n }\n try {\n this.startAdFailsafeTimer(requestToken);\n await this.adPlayer.play();\n if (this.expectedAdBreakDurationMs != null && this.adStopTimerId == null) {\n this.scheduleAdStopCountdown(this.getRemainingAdMs());\n }\n const currentMuted = this.video.muted;\n const currentVolume = this.video.volume;\n const adVolume = currentMuted ? 0 : currentVolume;\n this.adPlayer.setAdVolume(adVolume);\n this.consecutiveFailures = 0;\n this.temporaryFailureUrls.delete(vastTagUrl);\n } catch (playError) {\n if (this.config.debugAdTiming) {\n console.error(\"[AD-ERROR] Failed to play ad:\", playError);\n }\n const preloadedFallback = this.getPreloadedAd();\n if (preloadedFallback) {\n if (this.config.debugAdTiming) {\n console.log(\"[AD-ERROR] Play failed, trying preloaded fallback ad\");\n }\n try {\n this.clearAdFailsafeTimer();\n this.adPlayer.destroy();\n this.video.muted = true;\n this.video.volume = 0;\n this.adPlayer = preloadedFallback.adController;\n this.attachImaEventListeners();\n this.adPlayer.resume();\n this.consecutiveFailures = 0;\n this.currentAdIndex++;\n this.totalAdRequestsInBreak++;\n await this.adPlayer.play();\n if (this.expectedAdBreakDurationMs != null && this.adStopTimerId == null) {\n this.scheduleAdStopCountdown(this.getRemainingAdMs());\n }\n const currentMuted = this.video.muted;\n const currentVolume = this.video.volume;\n const adVolume = currentMuted ? 0 : currentVolume;\n this.adPlayer.setAdVolume(adVolume);\n return;\n } catch (fallbackError) {\n if (this.config.debugAdTiming) {\n console.warn(\"[AD-ERROR] Preloaded fallback also failed:\", fallbackError);\n }\n }\n }\n if (this.isTemporaryAdError(playError)) {\n this.temporaryFailureUrls.set(vastTagUrl, Date.now());\n if (this.config.debugAdTiming) {\n console.log(\"[AD-ERROR] Temporary play error - URL can be retried after cooldown\");\n }\n } else {\n this.failedVastUrls.add(vastTagUrl);\n if (this.config.debugAdTiming) {\n console.log(\"[AD-ERROR] Permanent play error - URL blacklisted\");\n }\n }\n this.clearAdFailsafeTimer();\n if (this.activeAdRequestToken === requestToken) {\n this.activeAdRequestToken = null;\n }\n throw playError;\n }\n } catch (error) {\n const errorMessage = error?.message || \"\";\n if (this.config.debugAdTiming) {\n console.error(\"[AD-ERROR] Ad request failed:\", errorMessage);\n }\n const preloadedFallback = this.getPreloadedAd();\n if (preloadedFallback) {\n if (this.config.debugAdTiming) {\n console.log(\"[AD-ERROR] Request failed, trying preloaded fallback ad\");\n }\n try {\n this.clearAdRequestWatchdog();\n this.clearAdFailsafeTimer();\n this.adPlayer.destroy();\n this.video.muted = true;\n this.video.volume = 0;\n this.adPlayer = preloadedFallback.adController;\n this.attachImaEventListeners();\n this.adPlayer.resume();\n this.consecutiveFailures = 0;\n this.currentAdIndex++;\n this.totalAdRequestsInBreak++;\n await this.adPlayer.play();\n const currentMuted = this.video.muted;\n const currentVolume = this.video.volume;\n const adVolume = currentMuted ? 0 : currentVolume;\n this.adPlayer.setAdVolume(adVolume);\n return;\n } catch (fallbackError) {\n if (this.config.debugAdTiming) {\n console.warn(\"[AD-ERROR] Preloaded fallback also failed:\", fallbackError);\n }\n }\n }\n if (this.isTemporaryAdError(error)) {\n this.temporaryFailureUrls.set(vastTagUrl, Date.now());\n if (this.config.debugAdTiming) {\n console.log(\"[AD-ERROR] Temporary error (no-fill/timeout) - URL can be retried after cooldown\");\n }\n } else {\n this.failedVastUrls.add(vastTagUrl);\n if (this.config.debugAdTiming) {\n console.log(\"[AD-ERROR] Permanent error - URL blacklisted:\", errorMessage);\n }\n }\n this.clearAdRequestWatchdog();\n this.clearAdFailsafeTimer();\n if (this.activeAdRequestToken === requestToken) {\n this.activeAdRequestToken = null;\n }\n throw error;\n }\n }\n handleAdPodComplete() {\n if (this.config.debugAdTiming) {\n console.log(\"[StormcloudVideoPlayer] \\u{1F3C1} Ad pod complete - cleaning up\");\n }\n this.clearAdRequestWatchdog();\n this.clearAdFailsafeTimer();\n this.activeAdRequestToken = null;\n this.stopContinuousFetching();\n this.stopPreloadPool();\n this.clearPendingAdBreak();\n if (this.isShowingPlaceholder) {\n this.adPlayer.hidePlaceholder();\n this.isShowingPlaceholder = false;\n }\n this.adRequestQueue = [];\n this.inAdBreak = false;\n this.adDetectSentForCurrentBreak = false;\n this.activeScte35BreakKey = void 0;\n this.scheduledScte35BreakKey = void 0;\n this.expectedAdBreakDurationMs = void 0;\n this.currentAdBreakStartWallClockMs = void 0;\n this.clearAdStartTimer();\n this.clearAdStopTimer();\n this.adPodQueue = [];\n this.showAds = false;\n this.currentAdIndex = 0;\n this.totalAdsInBreak = 0;\n this.consecutiveFailures = 0;\n this.globalConsecutiveNoFills = 0;\n this.adPlayer.stop().catch(() => {\n });\n const restoredMuted = this.adPlayer.getOriginalMutedState();\n const restoredVolume = this.adPlayer.getOriginalVolume();\n if (this.video.muted !== restoredMuted) {\n this.video.muted = restoredMuted;\n }\n if (Math.abs(this.video.volume - restoredVolume) > 0.01) {\n this.video.volume = restoredVolume;\n }\n if (this.shouldContinueLiveStreamDuringAds()) {\n if (this.video.paused) {\n if (this.config.debugAdTiming) {\n console.log(\"[StormcloudVideoPlayer] Content video paused in live mode after ads, resuming playback\");\n }\n this.video.play()?.catch(() => {\n });\n } else {\n if (this.config.debugAdTiming) {\n console.log(\"[StormcloudVideoPlayer] Content video already playing in live mode after ads\");\n }\n }\n } else if (this.video.paused) {\n this.video.play()?.catch(() => {\n });\n }\n }\n handleAdFailure() {\n this.consecutiveFailures++;\n this.recordGamNoFill();\n const remaining = this.getRemainingAdMs();\n if (this.config.debugAdTiming) {\n console.log(\n `[CONTINUOUS-FETCH] Ad failure: remaining=${remaining}ms, queued ads=${this.adRequestQueue.length}, consecutiveFailures=${this.consecutiveFailures}`,\n this.adRequestQueue.length > 0 ? { queuedUrls: [...this.adRequestQueue] } : {}\n );\n }\n if (this.consecutiveFailures >= this.maxConsecutiveFailures) {\n if (this.config.debugAdTiming) {\n console.log(`[CONTINUOUS-FETCH] \\u{1F6D1} Max consecutive failures reached (${this.consecutiveFailures}), ending ad break gracefully`);\n }\n this.handleAdPodComplete();\n return;\n }\n if (remaining > 500) {\n this.tryNextAvailableAdWithRateLimit();\n } else {\n if (this.config.debugAdTiming) {\n console.log(\"[AD-ERROR] Ad failed and no time remaining. Failed URLs:\", this.failedVastUrls.size);\n }\n this.handleAdPodComplete();\n }\n }\n startAdRequestWatchdog(token) {\n this.clearAdRequestWatchdog();\n const timeoutMs = this.config.adFailsafeTimeoutMs ?? 1e4;\n this.adRequestWatchdogToken = token;\n this.adRequestWatchdogId = window.setTimeout(() => {\n if (this.adRequestWatchdogToken !== token) {\n return;\n }\n this.adRequestWatchdogId = void 0;\n this.adRequestWatchdogToken = null;\n if (this.activeAdRequestToken === token) {\n this.activeAdRequestToken = null;\n }\n this.logAdState(\"ad_request_timeout\", { token, timeoutMs });\n this.handleAdFailure();\n }, timeoutMs);\n this.logAdState(\"ad_request_watchdog_started\", { token, timeoutMs });\n }\n clearAdRequestWatchdog() {\n if (this.adRequestWatchdogId != null) {\n clearTimeout(this.adRequestWatchdogId);\n this.adRequestWatchdogId = void 0;\n }\n if (this.adRequestWatchdogToken != null) {\n this.logAdState(\"ad_request_watchdog_cleared\", {\n token: this.adRequestWatchdogToken\n });\n this.adRequestWatchdogToken = null;\n }\n }\n startAdFailsafeTimer(token) {\n this.clearAdFailsafeTimer();\n const failsafeMs = this.config.adFailsafeTimeoutMs ?? 1e4;\n this.adFailsafeToken = token;\n this.adFailsafeTimerId = window.setTimeout(() => {\n if (this.adFailsafeToken !== token) {\n return;\n }\n this.adFailsafeTimerId = void 0;\n this.adFailsafeToken = null;\n if (this.activeAdRequestToken === token) {\n this.activeAdRequestToken = null;\n }\n this.logAdState(\"ad_failsafe_triggered\", {\n token,\n failsafeMs,\n videoPaused: this.video.paused,\n imaAdPlaying: this.adPlayer.isAdPlaying()\n });\n this.handleAdFailure();\n }, failsafeMs);\n this.logAdState(\"ad_failsafe_started\", { token, failsafeMs });\n }\n clearAdFailsafeTimer() {\n if (this.adFailsafeTimerId != null) {\n clearTimeout(this.adFailsafeTimerId);\n this.logAdState(\"ad_failsafe_cleared\", { token: this.adFailsafeToken });\n this.adFailsafeTimerId = void 0;\n }\n this.adFailsafeToken = null;\n }\n selectVastTagsForBreak(b) {\n if (!b || !b.vastTagUrl) return void 0;\n if (b.vastTagUrl.includes(\",\")) {\n return b.vastTagUrl.split(\",\").map((s) => s.trim()).filter((s) => s.length > 0);\n }\n return [b.vastTagUrl];\n }\n logAdState(event, extra = {}) {\n if (!this.config.debugAdTiming) {\n return;\n }\n console.log(\"[StormcloudVideoPlayer][AdState]\", {\n event,\n timestamp: (/* @__PURE__ */ new Date()).toISOString(),\n showAds: this.showAds,\n adPlaying: this.adPlayer.isAdPlaying(),\n inAdBreak: this.inAdBreak,\n activeAdRequestToken: this.activeAdRequestToken,\n ...extra\n });\n }\n getRemainingAdMs() {\n if (this.expectedAdBreakDurationMs == null || this.currentAdBreakStartWallClockMs == null)\n return 0;\n const elapsed = Date.now() - this.currentAdBreakStartWallClockMs;\n return Math.max(0, this.expectedAdBreakDurationMs - elapsed);\n }\n findBreakForTime(nowMs) {\n const schedule = this.vmapBreaks;\n const tol = this.config.driftToleranceMs ?? 1e3;\n for (const b of schedule) {\n if (this.consumedVmapBreakIds.has(this.getAdBreakKey(b))) {\n continue;\n }\n const breakStartMs = this.resolveBreakStartMs(b);\n if (breakStartMs == null) {\n continue;\n }\n const end = breakStartMs + (b.durationMs || 0);\n if (nowMs >= breakStartMs && (b.durationMs ? nowMs < end : nowMs <= breakStartMs + tol)) {\n return b;\n }\n }\n return void 0;\n }\n toggleMute() {\n if (this.adPlayer.isAdPlaying()) {\n const currentPerceptualState = this.isMuted();\n const newMutedState = !currentPerceptualState;\n this.adPlayer.updateOriginalMutedState(newMutedState, this.video.volume);\n this.adPlayer.setAdVolume(newMutedState ? 0 : 1);\n if (this.config.debugAdTiming) {\n console.log(\n \"[StormcloudVideoPlayer] Mute toggle during ad - immediately applied:\",\n newMutedState\n );\n }\n } else {\n this.video.muted = !this.video.muted;\n this.adPlayer.updateOriginalMutedState(this.video.muted, this.video.volume);\n if (this.config.debugAdTiming) {\n console.log(\"[StormcloudVideoPlayer] Muted:\", this.video.muted);\n }\n }\n }\n toggleFullscreen() {\n return new Promise((resolve, reject) => {\n if (!document.fullscreenElement) {\n const container = this.video.parentElement;\n if (!container) {\n reject(new Error(\"No parent container found for fullscreen\"));\n return;\n }\n container.requestFullscreen().then(() => {\n if (this.config.debugAdTiming) {\n console.log(\"[StormcloudVideoPlayer] Entered fullscreen\");\n }\n resolve();\n }).catch((err) => {\n if (this.config.debugAdTiming) {\n console.error(\"[StormcloudVideoPlayer] Fullscreen error:\", err);\n }\n reject(err);\n });\n } else {\n document.exitFullscreen().then(() => {\n if (this.config.debugAdTiming) {\n console.log(\"[StormcloudVideoPlayer] Exited fullscreen\");\n }\n resolve();\n }).catch((err) => {\n if (this.config.debugAdTiming) {\n console.error(\n \"[StormcloudVideoPlayer] Exit fullscreen error:\",\n err\n );\n }\n reject(err);\n });\n }\n });\n }\n isMuted() {\n if (this.adPlayer.isAdPlaying()) {\n if (this.config.debugAdTiming) {\n console.log(\n \"[StormcloudVideoPlayer] isMuted() override during ad playback -> false\"\n );\n }\n return false;\n }\n return this.video.muted;\n }\n setMuted(muted) {\n const adPlaying = this.adPlayer.isAdPlaying();\n if (adPlaying && muted === this.video.muted) {\n if (this.config.debugAdTiming) {\n console.log(\n \"[StormcloudVideoPlayer] setMuted reflective update during ad ignored\",\n { muted }\n );\n }\n return;\n }\n this.video.muted = muted;\n if (adPlaying) {\n this.adPlayer.updateOriginalMutedState(muted, this.video.volume);\n this.adPlayer.setAdVolume(muted ? 0 : 1);\n if (this.config.debugAdTiming) {\n console.log(\"[StormcloudVideoPlayer] setMuted applied during ad\", {\n muted\n });\n }\n return;\n }\n this.adPlayer.updateOriginalMutedState(muted, this.video.volume);\n if (this.config.debugAdTiming) {\n console.log(\"[StormcloudVideoPlayer] setMuted called:\", muted);\n }\n }\n setVolume(volume) {\n const clampedVolume = Math.max(0, Math.min(1, volume));\n const adPlaying = this.adPlayer.isAdPlaying();\n if (adPlaying) {\n this.adPlayer.setAdVolume(clampedVolume);\n this.adPlayer.updateOriginalMutedState(clampedVolume === 0, clampedVolume);\n if (this.config.debugAdTiming) {\n console.log(\"[StormcloudVideoPlayer] setVolume applied during ad\", {\n volume: clampedVolume\n });\n }\n } else {\n this.video.volume = clampedVolume;\n this.video.muted = clampedVolume === 0;\n this.adPlayer.updateOriginalMutedState(clampedVolume === 0, clampedVolume);\n if (this.config.debugAdTiming) {\n console.log(\"[StormcloudVideoPlayer] setVolume called:\", clampedVolume);\n }\n }\n }\n getVolume() {\n const adPlaying = this.adPlayer.isAdPlaying();\n if (adPlaying) {\n return this.adPlayer.getAdVolume();\n }\n return this.video.volume;\n }\n isFullscreen() {\n return !!document.fullscreenElement;\n }\n isLive() {\n return this.isLiveStream;\n }\n get videoElement() {\n return this.video;\n }\n resize() {\n if (this.config.debugAdTiming) {\n console.log(\"[StormcloudVideoPlayer] Resizing player\");\n }\n if (this.adPlayer && this.adPlayer.isAdPlaying()) {\n const width = this.video.clientWidth || 640;\n const height = this.video.clientHeight || 480;\n if (this.config.debugAdTiming) {\n console.log(\n `[StormcloudVideoPlayer] Resizing ads manager to ${width}x${height}`\n );\n }\n this.adPlayer.resize(width, height);\n }\n }\n destroy() {\n this.stopContinuousFetching();\n this.stopPreloadPool();\n this.clearAdStartTimer();\n this.clearAdStopTimer();\n this.clearAdFailsafeTimer();\n this.clearAdRequestWatchdog();\n this.clearPendingAdBreak();\n if (this.placeholderContainer) {\n if (this.placeholderContainer.parentElement) {\n this.placeholderContainer.parentElement.removeChild(this.placeholderContainer);\n }\n this.placeholderContainer = void 0;\n }\n if (this.timeUpdateHandler) {\n this.video.removeEventListener(\"timeupdate\", this.timeUpdateHandler);\n delete this.timeUpdateHandler;\n }\n if (this.emptiedHandler) {\n this.video.removeEventListener(\"emptied\", this.emptiedHandler);\n delete this.emptiedHandler;\n }\n if (this.heartbeatInterval) {\n clearInterval(this.heartbeatInterval);\n this.heartbeatInterval = void 0;\n }\n this.hls?.destroy();\n this.adPlayer?.destroy();\n if (this.palPlaybackStarted) {\n this.palPlaybackStarted = false;\n this.palNonce.sendPlaybackEnd();\n }\n this.palNonce.reset();\n this.adRequestQueue = [];\n this.consecutiveFailures = 0;\n }\n};\n\n// src/ui/StormcloudVideoPlayer.tsx\nvar import_fa = require(\"react-icons/fa\");\nvar import_jsx_runtime = require(\"react/jsx-runtime\");\nvar CRITICAL_PROPS = [\n \"src\",\n \"allowNativeHls\",\n \"licenseKey\",\n \"vmapUrl\",\n \"lowLatencyMode\",\n \"driftToleranceMs\",\n \"vastMode\"\n];\nvar CONTROLS_HIDE_DELAY = 3e3;\nvar DEFAULT_PLAYER_ASPECT_RATIO = 16 / 9;\nvar StormcloudVideoPlayerComponent = import_react.default.memo(\n (props) => {\n const {\n src,\n autoplay,\n muted,\n lowLatencyMode,\n allowNativeHls,\n driftToleranceMs,\n immediateManifestAds,\n debugAdTiming,\n showCustomControls,\n hideLoadingIndicator,\n onVolumeToggle,\n onFullscreenToggle,\n onControlClick,\n onReady,\n wrapperClassName,\n wrapperStyle,\n className,\n style,\n controls,\n playsInline,\n preload,\n poster,\n children,\n licenseKey,\n vastMode,\n vastTagUrl,\n vmapUrl,\n minSegmentsBeforePlay,\n ...restVideoAttrs\n } = props;\n const videoRef = (0, import_react.useRef)(null);\n const playerRef = (0, import_react.useRef)(null);\n const bufferingTimeoutRef = (0, import_react.useRef)(null);\n const controlsTimerRef = (0, import_react.useRef)(null);\n const wrapperRef = (0, import_react.useRef)(null);\n const [adStatus, setAdStatus] = import_react.default.useState({ showAds: false, currentIndex: 0, totalAds: 0, remainingSeconds: 0 });\n const [shouldShowNativeControls, setShouldShowNativeControls] = import_react.default.useState(true);\n const [isMuted, setIsMuted] = import_react.default.useState(false);\n const [isFullscreen, setIsFullscreen] = import_react.default.useState(false);\n const [isPlaying, setIsPlaying] = import_react.default.useState(false);\n const [currentTime, setCurrentTime] = import_react.default.useState(0);\n const [duration, setDuration] = import_react.default.useState(0);\n const [volume, setVolume] = import_react.default.useState(1);\n const [playbackRate, setPlaybackRate] = import_react.default.useState(1);\n const [showVolumeSlider, setShowVolumeSlider] = import_react.default.useState(false);\n const [showSpeedMenu, setShowSpeedMenu] = import_react.default.useState(false);\n const [isLoading, setIsLoading] = import_react.default.useState(true);\n const [isBuffering, setIsBuffering] = import_react.default.useState(false);\n const [showCenterPlay, setShowCenterPlay] = import_react.default.useState(false);\n const [showLicenseWarning, setShowLicenseWarning] = import_react.default.useState(false);\n const [controlsVisible, setControlsVisible] = import_react.default.useState(true);\n const [viewportWidth, setViewportWidth] = import_react.default.useState(\n typeof window !== \"undefined\" ? window.innerWidth : 1920\n );\n const [isPortrait, setIsPortrait] = import_react.default.useState(\n typeof window !== \"undefined\" ? window.innerHeight > window.innerWidth : false\n );\n const [playerAspectRatio, setPlayerAspectRatio] = import_react.default.useState(\n DEFAULT_PLAYER_ASPECT_RATIO\n );\n const getResponsiveScale = () => {\n if (viewportWidth < 480) return 0.7;\n if (viewportWidth < 768) return 0.8;\n if (viewportWidth < 1024) return 0.9;\n return 1;\n };\n const responsiveScale = getResponsiveScale();\n const resetControlsTimer = (0, import_react.useCallback)(() => {\n if (controlsTimerRef.current) {\n clearTimeout(controlsTimerRef.current);\n }\n setControlsVisible(true);\n controlsTimerRef.current = window.setTimeout(() => {\n if (!showVolumeSlider && !showSpeedMenu) {\n setControlsVisible(false);\n }\n }, CONTROLS_HIDE_DELAY);\n }, [showVolumeSlider, showSpeedMenu]);\n const handleWrapperMouseMove = (0, import_react.useCallback)(() => {\n resetControlsTimer();\n }, [resetControlsTimer]);\n const handleWrapperMouseLeave = (0, import_react.useCallback)(() => {\n if (!showVolumeSlider && !showSpeedMenu) {\n setControlsVisible(false);\n }\n }, [showVolumeSlider, showSpeedMenu]);\n const formatTime = (seconds) => {\n if (!isFinite(seconds)) return \"0:00:00\";\n const hours = Math.floor(seconds / 3600);\n const minutes = Math.floor(seconds % 3600 / 60);\n const remainingSeconds = Math.floor(seconds % 60);\n return `${hours}:${minutes.toString().padStart(2, \"0\")}:${remainingSeconds.toString().padStart(2, \"0\")}`;\n };\n const handlePlayPause = () => {\n if (videoRef.current) {\n if (videoRef.current.paused) {\n const hasValidSource = videoRef.current.src || videoRef.current.currentSrc && videoRef.current.currentSrc !== \"\" || videoRef.current.readyState >= 1;\n if (hasValidSource) {\n videoRef.current.play()?.catch((error) => {\n console.error(\"[StormcloudVideoPlayer] Failed to play:\", error);\n });\n setShowCenterPlay(false);\n } else {\n console.warn(\n \"[StormcloudVideoPlayer] Cannot play: video has no valid source\"\n );\n }\n } else {\n videoRef.current.pause();\n setShowCenterPlay(true);\n }\n }\n resetControlsTimer();\n };\n const handleCenterPlayClick = () => {\n if (videoRef.current && videoRef.current.paused) {\n const hasValidSource = videoRef.current.src || videoRef.current.currentSrc && videoRef.current.currentSrc !== \"\" || videoRef.current.readyState >= 1;\n if (hasValidSource) {\n videoRef.current.play()?.catch((error) => {\n console.error(\"[StormcloudVideoPlayer] Failed to play:\", error);\n });\n setShowCenterPlay(false);\n } else {\n console.warn(\n \"[StormcloudVideoPlayer] Cannot play: video has no valid source\"\n );\n }\n }\n };\n const handleTimelineSeek = (e) => {\n if (videoRef.current && duration > 0 && isFinite(duration)) {\n const rect = e.currentTarget.getBoundingClientRect();\n const clickX = e.clientX - rect.left;\n const progress = Math.max(0, Math.min(1, clickX / rect.width));\n const newTime = progress * duration;\n if (isFinite(newTime) && newTime >= 0 && newTime <= duration) {\n videoRef.current.currentTime = newTime;\n }\n }\n resetControlsTimer();\n };\n const handleVolumeChange = (newVolume) => {\n if (playerRef.current && isFinite(newVolume)) {\n const clampedVolume = Math.max(0, Math.min(1, newVolume));\n playerRef.current.setVolume(clampedVolume);\n }\n };\n const handlePlaybackRateChange = (rate) => {\n if (videoRef.current && isFinite(rate) && rate > 0) {\n videoRef.current.playbackRate = rate;\n }\n setShowSpeedMenu(false);\n };\n const isHlsStream = src?.toLowerCase().includes(\".m3u8\") || src?.toLowerCase().includes(\"/hls/\");\n const shouldShowEnhancedControls = showCustomControls && (isHlsStream ? allowNativeHls : true);\n const criticalPropsKey = (0, import_react.useMemo)(() => {\n return CRITICAL_PROPS.map((prop) => `${prop}:${props[prop]}`).join(\"|\");\n }, [\n src,\n allowNativeHls,\n licenseKey,\n vmapUrl,\n lowLatencyMode,\n driftToleranceMs,\n vastMode\n ]);\n (0, import_react.useEffect)(() => {\n if (typeof window === \"undefined\") return;\n const el = videoRef.current;\n if (!el || !src) return;\n if (!licenseKey) {\n setShowLicenseWarning(true);\n setIsLoading(false);\n console.warn(\n \"StormcloudVideoPlayer: License key is required but not provided. Please set the licenseKey prop to use the player.\"\n );\n return;\n }\n setShowLicenseWarning(false);\n if (debugAdTiming) {\n console.log(\"[StormcloudUI] Initializing player, isLoading=true\");\n }\n if (playerRef.current) {\n try {\n playerRef.current.destroy();\n } catch {\n }\n playerRef.current = null;\n }\n const cfg = {\n src,\n videoElement: el\n };\n if (autoplay !== void 0) cfg.autoplay = autoplay;\n if (muted !== void 0) cfg.muted = muted;\n if (lowLatencyMode !== void 0) cfg.lowLatencyMode = lowLatencyMode;\n if (allowNativeHls !== void 0) cfg.allowNativeHls = allowNativeHls;\n if (driftToleranceMs !== void 0)\n cfg.driftToleranceMs = driftToleranceMs;\n if (immediateManifestAds !== void 0)\n cfg.immediateManifestAds = immediateManifestAds;\n if (debugAdTiming !== void 0) cfg.debugAdTiming = debugAdTiming;\n if (showCustomControls !== void 0)\n cfg.showCustomControls = showCustomControls;\n if (onVolumeToggle !== void 0) cfg.onVolumeToggle = onVolumeToggle;\n if (onFullscreenToggle !== void 0)\n cfg.onFullscreenToggle = onFullscreenToggle;\n if (onControlClick !== void 0) cfg.onControlClick = onControlClick;\n if (licenseKey !== void 0) cfg.licenseKey = licenseKey;\n if (vastMode !== void 0) cfg.vastMode = vastMode;\n if (vastTagUrl !== void 0) cfg.vastTagUrl = vastTagUrl;\n if (vmapUrl !== void 0) cfg.vmapUrl = vmapUrl;\n if (minSegmentsBeforePlay !== void 0)\n cfg.minSegmentsBeforePlay = minSegmentsBeforePlay;\n const player = new StormcloudVideoPlayer(cfg);\n playerRef.current = player;\n player.load().then(() => {\n const showNative = player.shouldShowNativeControls();\n setShouldShowNativeControls(showNative);\n if (debugAdTiming) {\n console.log(\n \"[StormcloudUI] Player loaded successfully, waiting for video ready\"\n );\n }\n onReady?.(player);\n }).catch((error) => {\n console.error(\n \"StormcloudVideoPlayer: Failed to load player:\",\n error\n );\n setIsLoading(false);\n onReady?.(player);\n });\n return () => {\n try {\n player.destroy();\n } catch {\n }\n playerRef.current = null;\n };\n }, [criticalPropsKey]);\n (0, import_react.useEffect)(() => {\n if (!playerRef.current) return;\n try {\n if (autoplay !== void 0 && playerRef.current.videoElement) {\n playerRef.current.videoElement.autoplay = autoplay;\n }\n if (muted !== void 0 && !playerRef.current.isShowingAds()) {\n playerRef.current.setMuted(muted);\n }\n } catch (error) {\n console.warn(\"Failed to update player properties:\", error);\n }\n }, [autoplay, muted]);\n (0, import_react.useEffect)(() => {\n if (!playerRef.current) return;\n const checkAdStatus = () => {\n if (playerRef.current) {\n const showAdsFromMethod = playerRef.current.isShowingAds();\n const showAdsFromAttribute = videoRef.current?.dataset?.stormcloudAdPlaying === \"true\";\n const showAds = showAdsFromMethod || showAdsFromAttribute;\n const currentIndex = playerRef.current.getCurrentAdIndex();\n const totalAds = playerRef.current.getTotalAdsInBreak();\n const remainingMs = playerRef.current.getAdRemainingMs();\n const remainingSeconds = showAds ? Math.max(0, Math.ceil(remainingMs / 1e3)) : 0;\n setAdStatus((prev) => {\n if (prev.showAds !== showAds || prev.currentIndex !== currentIndex || prev.totalAds !== totalAds || prev.remainingSeconds !== remainingSeconds) {\n if (showAds && !prev.showAds) {\n setShowCenterPlay(false);\n }\n return { showAds, currentIndex, totalAds, remainingSeconds };\n }\n return prev;\n });\n }\n };\n const interval = setInterval(checkAdStatus, 50);\n return () => clearInterval(interval);\n }, []);\n (0, import_react.useEffect)(() => {\n if (typeof window === \"undefined\" || !playerRef.current) return;\n const handleResize = () => {\n if (playerRef.current && videoRef.current) {\n if (typeof playerRef.current.resize === \"function\") {\n playerRef.current.resize();\n }\n }\n setViewportWidth(window.innerWidth);\n setIsPortrait(window.innerHeight > window.innerWidth);\n };\n window.addEventListener(\"resize\", handleResize);\n return () => window.removeEventListener(\"resize\", handleResize);\n }, []);\n (0, import_react.useEffect)(() => {\n if (!playerRef.current || !videoRef.current) return;\n const updateStates = () => {\n if (playerRef.current && videoRef.current) {\n setIsMuted(playerRef.current.isMuted());\n setIsPlaying(!videoRef.current.paused);\n const currentTimeValue = videoRef.current.currentTime;\n setCurrentTime(isFinite(currentTimeValue) ? currentTimeValue : 0);\n const durationValue = videoRef.current.duration;\n setDuration(isFinite(durationValue) ? durationValue : 0);\n const volumeValue = playerRef.current.getVolume();\n setVolume(\n isFinite(volumeValue) ? Math.max(0, Math.min(1, volumeValue)) : 1\n );\n const rateValue = videoRef.current.playbackRate;\n setPlaybackRate(\n isFinite(rateValue) && rateValue > 0 ? rateValue : 1\n );\n }\n setIsFullscreen(\n document.fullscreenElement === wrapperRef.current\n );\n };\n const interval = setInterval(updateStates, 200);\n const handleFullscreenChange = () => {\n setIsFullscreen(\n document.fullscreenElement === wrapperRef.current\n );\n };\n document.addEventListener(\"fullscreenchange\", handleFullscreenChange);\n return () => {\n clearInterval(interval);\n document.removeEventListener(\n \"fullscreenchange\",\n handleFullscreenChange\n );\n };\n }, []);\n (0, import_react.useEffect)(() => {\n if (!videoRef.current) return;\n const handleLoadedMetadata = () => {\n const video2 = videoRef.current;\n if (video2) {\n if (video2.videoWidth > 0 && video2.videoHeight > 0) {\n setPlayerAspectRatio(video2.videoWidth / video2.videoHeight);\n }\n void video2.offsetHeight;\n }\n if (debugAdTiming) {\n console.log(\n \"[StormcloudUI] Video event: loadedmetadata, readyState:\",\n videoRef.current?.readyState\n );\n }\n };\n const handleLoadedData = () => {\n if (debugAdTiming) {\n console.log(\n \"[StormcloudUI] Video event: loadeddata, readyState:\",\n videoRef.current?.readyState\n );\n }\n };\n const handleLoadStart = () => {\n if (debugAdTiming) {\n console.log(\n \"[StormcloudUI] Video event: loadstart, readyState:\",\n videoRef.current?.readyState\n );\n }\n };\n const handleCanPlay = () => {\n setIsLoading(false);\n if (bufferingTimeoutRef.current) {\n clearTimeout(bufferingTimeoutRef.current);\n bufferingTimeoutRef.current = null;\n }\n setIsBuffering(false);\n if (debugAdTiming) {\n console.log(\n \"[StormcloudUI] Video event: canplay, readyState:\",\n videoRef.current?.readyState,\n \"- clearing loading state, isLoading=false\"\n );\n }\n };\n const handleCanPlayThrough = () => {\n setIsLoading(false);\n if (bufferingTimeoutRef.current) {\n clearTimeout(bufferingTimeoutRef.current);\n bufferingTimeoutRef.current = null;\n }\n setIsBuffering(false);\n if (debugAdTiming) {\n console.log(\n \"[StormcloudUI] Video event: canplaythrough, readyState:\",\n videoRef.current?.readyState,\n \"- clearing loading state, isLoading=false\"\n );\n }\n };\n const handleWaiting = () => {\n if (bufferingTimeoutRef.current) {\n clearTimeout(bufferingTimeoutRef.current);\n }\n bufferingTimeoutRef.current = window.setTimeout(() => {\n setIsBuffering(true);\n if (debugAdTiming) {\n console.log(\n \"[StormcloudUI] Video buffering detected (after 300ms delay), readyState:\",\n videoRef.current?.readyState,\n \"- showing spinner, isBuffering=true\"\n );\n }\n }, 300);\n if (debugAdTiming) {\n console.log(\n \"[StormcloudUI] Video event: waiting, readyState:\",\n videoRef.current?.readyState,\n \"- buffering delay started (300ms)\"\n );\n }\n };\n const handlePlaying = () => {\n setIsLoading(false);\n if (bufferingTimeoutRef.current) {\n clearTimeout(bufferingTimeoutRef.current);\n bufferingTimeoutRef.current = null;\n }\n setIsBuffering(false);\n setShowCenterPlay(false);\n if (debugAdTiming) {\n console.log(\n \"[StormcloudUI] Video event: playing, readyState:\",\n videoRef.current?.readyState,\n \"- playback started, isLoading=false, isBuffering=false\"\n );\n }\n };\n const handlePause = () => {\n const isAdActive = playerRef.current?.isShowingAds() || videoRef.current?.dataset?.stormcloudAdPlaying === \"true\";\n if (playerRef.current && !isAdActive) {\n setShowCenterPlay(true);\n } else {\n setShowCenterPlay(false);\n }\n };\n const handleEnded = () => {\n setShowCenterPlay(true);\n };\n const video = videoRef.current;\n video.addEventListener(\"loadstart\", handleLoadStart);\n video.addEventListener(\"loadedmetadata\", handleLoadedMetadata);\n video.addEventListener(\"loadeddata\", handleLoadedData);\n video.addEventListener(\"canplay\", handleCanPlay);\n video.addEventListener(\"canplaythrough\", handleCanPlayThrough);\n video.addEventListener(\"waiting\", handleWaiting);\n video.addEventListener(\"playing\", handlePlaying);\n video.addEventListener(\"pause\", handlePause);\n video.addEventListener(\"ended\", handleEnded);\n if (video.paused) {\n setShowCenterPlay(true);\n }\n return () => {\n if (bufferingTimeoutRef.current) {\n clearTimeout(bufferingTimeoutRef.current);\n bufferingTimeoutRef.current = null;\n }\n video.removeEventListener(\"loadstart\", handleLoadStart);\n video.removeEventListener(\"loadedmetadata\", handleLoadedMetadata);\n video.removeEventListener(\"loadeddata\", handleLoadedData);\n video.removeEventListener(\"canplay\", handleCanPlay);\n video.removeEventListener(\"canplaythrough\", handleCanPlayThrough);\n video.removeEventListener(\"waiting\", handleWaiting);\n video.removeEventListener(\"playing\", handlePlaying);\n video.removeEventListener(\"pause\", handlePause);\n video.removeEventListener(\"ended\", handleEnded);\n };\n }, [debugAdTiming]);\n (0, import_react.useEffect)(() => {\n setPlayerAspectRatio(DEFAULT_PLAYER_ASPECT_RATIO);\n }, [src]);\n (0, import_react.useEffect)(() => {\n return () => {\n if (controlsTimerRef.current) {\n clearTimeout(controlsTimerRef.current);\n }\n };\n }, []);\n const progressPercent = duration > 0 ? currentTime / duration * 100 : 0;\n const VolumeIcon = isMuted || volume === 0 ? import_fa.FaVolumeMute : volume < 0.5 ? import_fa.FaVolumeDown : import_fa.FaVolumeUp;\n return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(import_jsx_runtime.Fragment, { children: [\n /* @__PURE__ */ (0, import_jsx_runtime.jsx)(\"style\", { children: `\n @keyframes sc-spin {\n from { transform: rotate(0deg); }\n to { transform: rotate(360deg); }\n }\n @keyframes sc-loading-glow {\n 0%, 100% { opacity: 0.85; transform: scale(1); }\n 50% { opacity: 1; transform: scale(1.05); }\n }\n @keyframes sc-pulse {\n 0%, 100% { opacity: 1; }\n 50% { opacity: 0.6; }\n }\n @keyframes sc-fade-in {\n from { opacity: 0; transform: translateY(8px); }\n to { opacity: 1; transform: translateY(0); }\n }\n .sc-wrapper:fullscreen,\n .sc-wrapper:has(*:fullscreen) {\n border-radius: 0 !important;\n box-shadow: none !important;\n width: 100vw !important;\n height: 100vh !important;\n max-width: 100vw !important;\n max-height: 100vh !important;\n position: fixed !important;\n top: 0 !important;\n left: 0 !important;\n z-index: 999999 !important;\n background: #000 !important;\n display: flex !important;\n align-items: center !important;\n justify-content: center !important;\n }\n .sc-ctrl-btn {\n background: none;\n border: none;\n color: #fff;\n cursor: pointer;\n display: flex;\n align-items: center;\n justify-content: center;\n border-radius: 50%;\n padding: 8px;\n transition: background 0.15s ease, opacity 0.15s ease;\n opacity: 0.9;\n }\n .sc-ctrl-btn:hover {\n opacity: 1;\n background: rgba(255, 255, 255, 0.1);\n }\n .sc-ctrl-btn:active {\n opacity: 0.7;\n }\n .sc-controls-bar {\n transition: opacity 0.35s ease, transform 0.35s ease;\n }\n .sc-progress-track:hover .sc-progress-thumb {\n transform: translate(-50%, -50%) scale(1) !important;\n }\n .sc-loading-hidden .sc-loading-indicator {\n display: none !important;\n }\n ` }),\n /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(\n \"div\",\n {\n ref: wrapperRef,\n className: `sc-wrapper ${wrapperClassName || \"\"}`,\n onMouseMove: handleWrapperMouseMove,\n onMouseLeave: handleWrapperMouseLeave,\n style: {\n display: \"flex\",\n alignItems: \"center\",\n justifyContent: \"center\",\n position: isFullscreen ? \"fixed\" : \"relative\",\n top: isFullscreen ? 0 : void 0,\n left: isFullscreen ? 0 : void 0,\n overflow: \"hidden\",\n width: isFullscreen ? \"100vw\" : \"100%\",\n height: isFullscreen ? \"100vh\" : \"auto\",\n minHeight: isFullscreen ? \"100vh\" : \"auto\",\n aspectRatio: isFullscreen ? void 0 : playerAspectRatio,\n maxWidth: isFullscreen ? \"100vw\" : \"100%\",\n maxHeight: isFullscreen ? \"100vh\" : \"none\",\n zIndex: isFullscreen ? 999999 : void 0,\n backgroundColor: \"#000\",\n borderRadius: isFullscreen ? 0 : void 0,\n boxShadow: isFullscreen ? \"none\" : void 0,\n ...wrapperStyle\n },\n children: [\n /* @__PURE__ */ (0, import_jsx_runtime.jsx)(\n \"video\",\n {\n ref: videoRef,\n className,\n style: {\n display: \"block\",\n width: \"100%\",\n height: \"100%\",\n maxWidth: \"100%\",\n maxHeight: isFullscreen ? \"100%\" : \"none\",\n objectFit: isFullscreen ? \"cover\" : \"contain\",\n backgroundColor: \"#000\",\n aspectRatio: isFullscreen ? \"unset\" : void 0,\n ...style\n },\n controls: shouldShowNativeControls && controls && !showCustomControls,\n playsInline,\n preload,\n poster,\n ...restVideoAttrs,\n children\n }\n ),\n (isLoading || isBuffering) && !hideLoadingIndicator && /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(\n \"div\",\n {\n className: \"sc-loading-indicator\",\n style: {\n position: \"absolute\",\n top: \"50%\",\n left: \"50%\",\n transform: \"translate(-50%, -50%)\",\n zIndex: 20,\n width: `${Math.max(34, 38 * responsiveScale)}px`,\n height: `${Math.max(34, 38 * responsiveScale)}px`,\n display: \"flex\",\n alignItems: \"center\",\n justifyContent: \"center\",\n animation: \"sc-loading-glow 1.4s ease-in-out infinite\",\n filter: \"drop-shadow(0 6px 14px rgba(0, 0, 0, 0.55))\"\n },\n children: [\n /* @__PURE__ */ (0, import_jsx_runtime.jsx)(\n \"div\",\n {\n style: {\n position: \"absolute\",\n inset: 0,\n borderRadius: \"50%\",\n border: \"3px solid rgba(255, 255, 255, 0.25)\",\n borderTopColor: \"#ff0000\",\n borderRightColor: \"rgba(255, 255, 255, 0.85)\",\n animation: \"sc-spin 0.8s linear infinite\"\n }\n }\n ),\n /* @__PURE__ */ (0, import_jsx_runtime.jsx)(\n \"div\",\n {\n style: {\n width: \"7px\",\n height: \"7px\",\n borderRadius: \"50%\",\n background: \"#ff0000\",\n boxShadow: \"0 0 10px rgba(255, 0, 0, 0.65)\"\n }\n }\n )\n ]\n }\n ),\n showLicenseWarning && /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(\n \"div\",\n {\n style: {\n position: \"absolute\",\n top: \"50%\",\n left: \"50%\",\n transform: \"translate(-50%, -50%)\",\n zIndex: 25,\n background: \"rgba(220, 38, 38, 0.92)\",\n backdropFilter: \"blur(24px)\",\n color: \"white\",\n padding: \"28px 36px\",\n borderRadius: \"14px\",\n border: \"1px solid rgba(255, 255, 255, 0.15)\",\n boxShadow: \"0 24px 64px rgba(0, 0, 0, 0.5)\",\n textAlign: \"center\",\n maxWidth: \"400px\",\n margin: \"0 16px\"\n },\n children: [\n /* @__PURE__ */ (0, import_jsx_runtime.jsx)(\"div\", { style: { fontSize: \"18px\", fontWeight: \"700\", marginBottom: \"10px\", letterSpacing: \"-0.02em\" }, children: \"License Key Required\" }),\n /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(\"div\", { style: { fontSize: \"13px\", lineHeight: \"1.6\", color: \"rgba(255, 255, 255, 0.85)\" }, children: [\n \"Please provide a valid license key to use the Stormcloud Video Player.\",\n /* @__PURE__ */ (0, import_jsx_runtime.jsx)(\"br\", {}),\n \"Contact your administrator for licensing information.\"\n ] })\n ]\n }\n ),\n adStatus.showAds && /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(\n \"div\",\n {\n style: {\n position: \"absolute\",\n top: `${12 * responsiveScale}px`,\n left: `${12 * responsiveScale}px`,\n zIndex: 50,\n display: \"flex\",\n alignItems: \"center\",\n gap: \"8px\",\n pointerEvents: \"none\",\n animation: \"sc-fade-in 0.3s ease\"\n },\n children: [\n /* @__PURE__ */ (0, import_jsx_runtime.jsx)(\n \"div\",\n {\n style: {\n background: \"rgba(234, 179, 8, 0.95)\",\n color: \"#111\",\n padding: `${4 * responsiveScale}px ${12 * responsiveScale}px`,\n borderRadius: \"6px\",\n fontSize: `${11 * responsiveScale}px`,\n fontWeight: 700,\n letterSpacing: \"0.08em\",\n textTransform: \"uppercase\",\n boxShadow: \"0 2px 12px rgba(234, 179, 8, 0.35)\"\n },\n children: \"Ad\"\n }\n ),\n /* @__PURE__ */ (0, import_jsx_runtime.jsx)(\n \"div\",\n {\n style: {\n background: \"rgba(0, 0, 0, 0.58)\",\n color: \"rgba(255, 255, 255, 0.92)\",\n padding: `${4 * responsiveScale}px ${10 * responsiveScale}px`,\n borderRadius: \"6px\",\n fontSize: `${11 * responsiveScale}px`,\n fontWeight: 600,\n border: \"1px solid rgba(255, 255, 255, 0.1)\",\n boxShadow: \"0 2px 10px rgba(0, 0, 0, 0.25)\"\n },\n children: `${Math.max(1, adStatus.currentIndex)} of ${Math.max(\n Math.max(1, adStatus.currentIndex),\n adStatus.totalAds\n )}`\n }\n )\n ]\n }\n ),\n showCenterPlay && !isLoading && !isBuffering && !showLicenseWarning && !adStatus.showAds && /* @__PURE__ */ (0, import_jsx_runtime.jsx)(\n \"div\",\n {\n onClick: handleCenterPlayClick,\n style: {\n position: \"absolute\",\n top: \"50%\",\n left: \"50%\",\n transform: \"translate(-50%, -50%)\",\n zIndex: 15,\n cursor: \"pointer\",\n background: \"rgba(0, 0, 0, 0.55)\",\n backdropFilter: \"blur(8px)\",\n borderRadius: \"50%\",\n width: `${92 * responsiveScale}px`,\n height: `${92 * responsiveScale}px`,\n display: \"flex\",\n alignItems: \"center\",\n justifyContent: \"center\",\n transition: \"background 0.2s ease, transform 0.2s ease\",\n animation: \"sc-fade-in 0.2s ease\"\n },\n onMouseEnter: (e) => {\n e.currentTarget.style.background = \"rgba(0, 0, 0, 0.72)\";\n e.currentTarget.style.transform = \"translate(-50%, -50%) scale(1.06)\";\n },\n onMouseLeave: (e) => {\n e.currentTarget.style.background = \"rgba(0, 0, 0, 0.55)\";\n e.currentTarget.style.transform = \"translate(-50%, -50%) scale(1)\";\n },\n title: \"Play\",\n children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(\n import_fa.FaPlay,\n {\n size: Math.max(24, 32 * responsiveScale),\n color: \"white\",\n style: { marginLeft: \"4px\" }\n }\n )\n }\n ),\n shouldShowEnhancedControls && !showLicenseWarning ? /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(\n \"div\",\n {\n className: \"sc-controls-bar\",\n style: {\n position: \"absolute\",\n bottom: 0,\n left: 0,\n right: 0,\n background: \"linear-gradient(0deg, rgba(0, 0, 0, 0.8) 0%, rgba(0, 0, 0, 0.35) 60%, transparent 100%)\",\n padding: `${20 * responsiveScale}px ${12 * responsiveScale}px ${8 * responsiveScale}px`,\n zIndex: 10,\n opacity: controlsVisible || adStatus.showAds ? 1 : 0,\n transform: controlsVisible || adStatus.showAds ? \"translateY(0)\" : \"translateY(6px)\",\n pointerEvents: controlsVisible || adStatus.showAds ? \"auto\" : \"none\"\n },\n children: [\n /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(\n \"div\",\n {\n className: \"sc-progress-track\",\n style: {\n width: \"100%\",\n height: \"3px\",\n background: \"rgba(255, 255, 255, 0.2)\",\n borderRadius: \"1.5px\",\n marginBottom: `${8 * responsiveScale}px`,\n cursor: \"pointer\",\n position: \"relative\",\n transition: \"height 0.1s ease\"\n },\n onClick: handleTimelineSeek,\n onMouseEnter: (e) => {\n e.currentTarget.style.height = \"5px\";\n },\n onMouseLeave: (e) => {\n e.currentTarget.style.height = \"3px\";\n },\n children: [\n /* @__PURE__ */ (0, import_jsx_runtime.jsx)(\n \"div\",\n {\n style: {\n position: \"absolute\",\n top: 0,\n left: 0,\n bottom: 0,\n background: adStatus.showAds ? \"#f5c518\" : \"#ff0000\",\n borderRadius: \"1.5px\",\n width: `${progressPercent}%`,\n transition: \"width 0.15s linear\"\n }\n }\n ),\n /* @__PURE__ */ (0, import_jsx_runtime.jsx)(\n \"div\",\n {\n className: \"sc-progress-thumb\",\n style: {\n position: \"absolute\",\n top: \"50%\",\n left: `${progressPercent}%`,\n transform: \"translate(-50%, -50%) scale(0)\",\n width: \"13px\",\n height: \"13px\",\n background: adStatus.showAds ? \"#f5c518\" : \"#ff0000\",\n borderRadius: \"50%\",\n boxShadow: \"0 0 4px rgba(0, 0, 0, 0.3)\",\n transition: \"transform 0.1s ease, left 0.15s linear\"\n }\n }\n )\n ]\n }\n ),\n /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(\n \"div\",\n {\n style: {\n display: \"flex\",\n alignItems: \"center\",\n justifyContent: \"space-between\",\n color: \"white\",\n gap: `${8 * responsiveScale}px`\n },\n children: [\n /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(\n \"div\",\n {\n style: {\n display: \"flex\",\n alignItems: \"center\",\n gap: `${8 * responsiveScale}px`\n },\n children: [\n /* @__PURE__ */ (0, import_jsx_runtime.jsx)(\n \"button\",\n {\n className: \"sc-ctrl-btn\",\n onClick: handlePlayPause,\n style: {\n padding: `${8 * responsiveScale}px`,\n borderRadius: \"50%\",\n minWidth: `${36 * responsiveScale}px`,\n minHeight: `${36 * responsiveScale}px`\n },\n title: isPlaying ? \"Pause\" : \"Play\",\n children: isPlaying ? /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_fa.FaPause, { size: Math.max(14, 18 * responsiveScale) }) : /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_fa.FaPlay, { size: Math.max(14, 18 * responsiveScale), style: { marginLeft: \"2px\" } })\n }\n ),\n /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(\n \"div\",\n {\n style: {\n display: \"flex\",\n alignItems: \"center\",\n paddingRight: `${6 * responsiveScale}px`\n },\n onMouseEnter: () => setShowVolumeSlider(true),\n onMouseLeave: () => setShowVolumeSlider(false),\n children: [\n /* @__PURE__ */ (0, import_jsx_runtime.jsx)(\n \"button\",\n {\n className: \"sc-ctrl-btn\",\n onClick: () => {\n if (playerRef.current) playerRef.current.toggleMute();\n onVolumeToggle?.();\n resetControlsTimer();\n },\n style: {\n padding: `${8 * responsiveScale}px`,\n borderRadius: \"50%\",\n minWidth: `${36 * responsiveScale}px`,\n minHeight: `${36 * responsiveScale}px`\n },\n title: isMuted ? \"Unmute\" : \"Mute\",\n children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(VolumeIcon, { size: Math.max(14, 18 * responsiveScale) })\n }\n ),\n /* @__PURE__ */ (0, import_jsx_runtime.jsx)(\n \"div\",\n {\n style: {\n width: showVolumeSlider ? `${68 * responsiveScale}px` : \"0px\",\n overflow: \"hidden\",\n transition: \"width 0.2s cubic-bezier(0.4, 0, 0.2, 1)\",\n display: \"flex\",\n alignItems: \"center\",\n paddingLeft: showVolumeSlider ? `${3 * responsiveScale}px` : \"0\",\n paddingRight: showVolumeSlider ? `${8 * responsiveScale}px` : \"0\"\n },\n children: /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(\n \"div\",\n {\n style: {\n position: \"relative\",\n width: `${56 * responsiveScale}px`,\n height: \"3px\",\n cursor: \"pointer\",\n borderRadius: \"1.5px\"\n },\n onMouseDown: (e) => {\n e.preventDefault();\n const el = e.currentTarget;\n const move = (ev) => {\n const r2 = el.getBoundingClientRect();\n handleVolumeChange(Math.max(0, Math.min(1, (ev.clientX - r2.left) / r2.width)));\n };\n const up = () => {\n document.removeEventListener(\"mousemove\", move);\n document.removeEventListener(\"mouseup\", up);\n };\n document.addEventListener(\"mousemove\", move);\n document.addEventListener(\"mouseup\", up);\n const r = el.getBoundingClientRect();\n handleVolumeChange(Math.max(0, Math.min(1, (e.clientX - r.left) / r.width)));\n },\n onClick: (e) => {\n e.stopPropagation();\n const r = e.currentTarget.getBoundingClientRect();\n handleVolumeChange(Math.max(0, Math.min(1, (e.clientX - r.left) / r.width)));\n },\n children: [\n /* @__PURE__ */ (0, import_jsx_runtime.jsx)(\"div\", { style: { position: \"absolute\", inset: 0, background: \"rgba(255, 255, 255, 0.2)\", borderRadius: \"1.5px\" } }),\n /* @__PURE__ */ (0, import_jsx_runtime.jsx)(\n \"div\",\n {\n style: {\n position: \"absolute\",\n top: 0,\n left: 0,\n bottom: 0,\n width: `${(isMuted ? 0 : volume) * 100}%`,\n background: \"#fff\",\n borderRadius: \"1.5px\",\n transition: \"width 0.1s ease-out\"\n }\n }\n ),\n /* @__PURE__ */ (0, import_jsx_runtime.jsx)(\n \"div\",\n {\n style: {\n position: \"absolute\",\n top: \"50%\",\n left: `${(isMuted ? 0 : volume) * 100}%`,\n transform: \"translate(-50%, -50%)\",\n width: \"12px\",\n height: \"12px\",\n background: \"#fff\",\n borderRadius: \"50%\",\n boxShadow: \"0 0 3px rgba(0, 0, 0, 0.3)\",\n transition: \"left 0.1s ease-out\"\n }\n }\n )\n ]\n }\n )\n }\n )\n ]\n }\n ),\n /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(\n \"div\",\n {\n style: {\n fontSize: `${13 * responsiveScale}px`,\n fontFamily: \"Roboto, 'Segoe UI', Arial, sans-serif\",\n color: \"rgba(255, 255, 255, 0.9)\",\n display: viewportWidth < 480 ? \"none\" : \"block\",\n fontVariantNumeric: \"tabular-nums\",\n userSelect: \"none\",\n marginLeft: `${4 * responsiveScale}px`\n },\n children: [\n formatTime(currentTime),\n \" \",\n /* @__PURE__ */ (0, import_jsx_runtime.jsx)(\"span\", { style: { color: \"rgba(255,255,255,0.5)\" }, children: \"/\" }),\n \" \",\n formatTime(duration)\n ]\n }\n )\n ]\n }\n ),\n /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(\n \"div\",\n {\n style: {\n display: \"flex\",\n alignItems: \"center\",\n gap: `${8 * responsiveScale}px`\n },\n children: [\n /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(\"div\", { style: { position: \"relative\", display: viewportWidth < 600 ? \"none\" : \"block\" }, children: [\n /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(\n \"button\",\n {\n className: \"sc-ctrl-btn\",\n onClick: () => {\n setShowSpeedMenu(!showSpeedMenu);\n resetControlsTimer();\n },\n style: {\n padding: `${6 * responsiveScale}px ${10 * responsiveScale}px`,\n borderRadius: `${6 * responsiveScale}px`,\n fontSize: `${13 * responsiveScale}px`,\n fontFamily: \"'SF Mono', 'Cascadia Code', monospace\",\n fontWeight: \"600\",\n minHeight: `${32 * responsiveScale}px`\n },\n title: \"Playback Speed\",\n children: [\n playbackRate,\n \"x\"\n ]\n }\n ),\n showSpeedMenu && /* @__PURE__ */ (0, import_jsx_runtime.jsx)(\n \"div\",\n {\n style: {\n position: \"absolute\",\n bottom: \"100%\",\n right: 0,\n marginBottom: \"8px\",\n background: \"rgba(0, 0, 0, 0.8)\",\n backdropFilter: \"blur(24px)\",\n WebkitBackdropFilter: \"blur(24px)\",\n borderRadius: \"10px\",\n border: \"1px solid rgba(255, 255, 255, 0.1)\",\n overflow: \"hidden\",\n minWidth: \"80px\",\n boxShadow: \"0 12px 40px rgba(0, 0, 0, 0.5)\",\n animation: \"sc-fade-in 0.15s ease\"\n },\n children: [0.25, 0.5, 0.75, 1, 1.25, 1.5, 1.75, 2].map((speed) => /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(\n \"button\",\n {\n onClick: () => handlePlaybackRateChange(speed),\n style: {\n display: \"block\",\n width: \"100%\",\n padding: `${8 * responsiveScale}px ${14 * responsiveScale}px`,\n background: playbackRate === speed ? \"rgba(255, 255, 255, 0.12)\" : \"transparent\",\n border: \"none\",\n color: playbackRate === speed ? \"#fff\" : \"rgba(255, 255, 255, 0.7)\",\n cursor: \"pointer\",\n fontSize: `${12 * responsiveScale}px`,\n fontFamily: \"'SF Mono', monospace\",\n fontWeight: playbackRate === speed ? \"700\" : \"500\",\n textAlign: \"center\",\n transition: \"background 0.15s ease, color 0.15s ease\"\n },\n onMouseEnter: (e) => {\n if (playbackRate !== speed) {\n e.target.style.background = \"rgba(255, 255, 255, 0.08)\";\n e.target.style.color = \"#fff\";\n }\n },\n onMouseLeave: (e) => {\n if (playbackRate !== speed) {\n e.target.style.background = \"transparent\";\n e.target.style.color = \"rgba(255, 255, 255, 0.7)\";\n }\n },\n children: [\n speed,\n \"x\"\n ]\n },\n speed\n ))\n }\n )\n ] }),\n /* @__PURE__ */ (0, import_jsx_runtime.jsx)(\n \"button\",\n {\n className: \"sc-ctrl-btn\",\n onClick: () => {\n if (onFullscreenToggle) {\n onFullscreenToggle();\n } else if (wrapperRef.current) {\n if (!document.fullscreenElement) {\n wrapperRef.current.requestFullscreen().catch(() => {\n });\n } else {\n document.exitFullscreen().catch(() => {\n });\n }\n }\n resetControlsTimer();\n },\n style: {\n padding: `${8 * responsiveScale}px`,\n borderRadius: \"50%\",\n minWidth: `${36 * responsiveScale}px`,\n minHeight: `${36 * responsiveScale}px`\n },\n title: isFullscreen ? \"Exit Fullscreen\" : \"Enter Fullscreen\",\n children: isFullscreen ? /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_fa.FaCompress, { size: Math.max(14, 18 * responsiveScale) }) : /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_fa.FaExpand, { size: Math.max(14, 18 * responsiveScale) })\n }\n )\n ]\n }\n )\n ]\n }\n )\n ]\n }\n ) : showCustomControls && !showLicenseWarning && /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(\n \"div\",\n {\n className: \"sc-controls-bar\",\n style: {\n position: \"absolute\",\n bottom: `${10 * responsiveScale}px`,\n right: `${10 * responsiveScale}px`,\n display: \"flex\",\n flexDirection: isPortrait ? \"column\" : \"row\",\n gap: `${8 * responsiveScale}px`,\n zIndex: 10,\n opacity: controlsVisible ? 1 : 0,\n transform: controlsVisible ? \"translateY(0)\" : \"translateY(4px)\",\n pointerEvents: controlsVisible ? \"auto\" : \"none\"\n },\n children: [\n /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(\n \"div\",\n {\n style: {\n display: \"flex\",\n alignItems: \"center\",\n background: \"rgba(0, 0, 0, 0.6)\",\n borderRadius: `${18 * responsiveScale}px`,\n padding: \"2px\",\n paddingRight: `${8 * responsiveScale}px`\n },\n onMouseEnter: () => setShowVolumeSlider(true),\n onMouseLeave: () => setShowVolumeSlider(false),\n children: [\n /* @__PURE__ */ (0, import_jsx_runtime.jsx)(\n \"button\",\n {\n className: \"sc-ctrl-btn\",\n onClick: () => {\n if (playerRef.current) playerRef.current.toggleMute();\n onVolumeToggle?.();\n resetControlsTimer();\n },\n style: {\n padding: `${8 * responsiveScale}px`,\n borderRadius: \"50%\",\n minWidth: `${36 * responsiveScale}px`,\n minHeight: `${36 * responsiveScale}px`\n },\n title: isMuted ? \"Unmute\" : \"Mute\",\n children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(VolumeIcon, { size: Math.max(14, 18 * responsiveScale) })\n }\n ),\n /* @__PURE__ */ (0, import_jsx_runtime.jsx)(\n \"div\",\n {\n style: {\n width: showVolumeSlider ? `${68 * responsiveScale}px` : \"0px\",\n overflow: \"hidden\",\n transition: \"width 0.2s cubic-bezier(0.4, 0, 0.2, 1)\",\n display: \"flex\",\n alignItems: \"center\",\n paddingLeft: showVolumeSlider ? `${3 * responsiveScale}px` : \"0\",\n paddingRight: showVolumeSlider ? `${10 * responsiveScale}px` : \"0\"\n },\n children: /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(\n \"div\",\n {\n style: {\n position: \"relative\",\n width: `${56 * responsiveScale}px`,\n height: \"3px\",\n cursor: \"pointer\",\n borderRadius: \"1.5px\"\n },\n onMouseDown: (e) => {\n e.preventDefault();\n const el = e.currentTarget;\n const move = (ev) => {\n const r2 = el.getBoundingClientRect();\n handleVolumeChange(Math.max(0, Math.min(1, (ev.clientX - r2.left) / r2.width)));\n };\n const up = () => {\n document.removeEventListener(\"mousemove\", move);\n document.removeEventListener(\"mouseup\", up);\n };\n document.addEventListener(\"mousemove\", move);\n document.addEventListener(\"mouseup\", up);\n const r = el.getBoundingClientRect();\n handleVolumeChange(Math.max(0, Math.min(1, (e.clientX - r.left) / r.width)));\n },\n onClick: (e) => {\n e.stopPropagation();\n const r = e.currentTarget.getBoundingClientRect();\n handleVolumeChange(Math.max(0, Math.min(1, (e.clientX - r.left) / r.width)));\n },\n children: [\n /* @__PURE__ */ (0, import_jsx_runtime.jsx)(\"div\", { style: { position: \"absolute\", inset: 0, background: \"rgba(255, 255, 255, 0.2)\", borderRadius: \"1.5px\" } }),\n /* @__PURE__ */ (0, import_jsx_runtime.jsx)(\n \"div\",\n {\n style: {\n position: \"absolute\",\n top: 0,\n left: 0,\n bottom: 0,\n width: `${(isMuted ? 0 : volume) * 100}%`,\n background: \"#fff\",\n borderRadius: \"1.5px\",\n transition: \"width 0.1s ease-out\"\n }\n }\n ),\n /* @__PURE__ */ (0, import_jsx_runtime.jsx)(\n \"div\",\n {\n style: {\n position: \"absolute\",\n top: \"50%\",\n left: `${(isMuted ? 0 : volume) * 100}%`,\n transform: \"translate(-50%, -50%)\",\n width: \"12px\",\n height: \"12px\",\n background: \"#fff\",\n borderRadius: \"50%\",\n boxShadow: \"0 0 3px rgba(0, 0, 0, 0.3)\",\n transition: \"left 0.1s ease-out\"\n }\n }\n )\n ]\n }\n )\n }\n )\n ]\n }\n ),\n /* @__PURE__ */ (0, import_jsx_runtime.jsx)(\n \"button\",\n {\n className: \"sc-ctrl-btn\",\n onClick: () => {\n if (onFullscreenToggle) {\n onFullscreenToggle();\n } else if (wrapperRef.current) {\n if (!document.fullscreenElement) {\n wrapperRef.current.requestFullscreen().catch(() => {\n });\n } else {\n document.exitFullscreen().catch(() => {\n });\n }\n }\n resetControlsTimer();\n },\n style: {\n padding: `${8 * responsiveScale}px`,\n borderRadius: \"50%\",\n minWidth: `${36 * responsiveScale}px`,\n minHeight: `${36 * responsiveScale}px`,\n background: \"rgba(0, 0, 0, 0.6)\"\n },\n title: isFullscreen ? \"Exit Fullscreen\" : \"Enter Fullscreen\",\n children: isFullscreen ? /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_fa.FaCompress, { size: Math.max(14, 18 * responsiveScale) }) : /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_fa.FaExpand, { size: Math.max(14, 18 * responsiveScale) })\n }\n )\n ]\n }\n ),\n onControlClick && /* @__PURE__ */ (0, import_jsx_runtime.jsx)(\n \"div\",\n {\n onClick: onControlClick,\n style: {\n position: \"absolute\",\n top: 0,\n left: 0,\n right: 0,\n bottom: 0,\n zIndex: 1,\n cursor: \"pointer\"\n }\n }\n )\n ]\n }\n )\n ] });\n },\n (prevProps, nextProps) => {\n for (const prop of CRITICAL_PROPS) {\n if (prevProps[prop] !== nextProps[prop]) {\n return false;\n }\n }\n const uiProps = [\n \"autoplay\",\n \"muted\",\n \"controls\",\n \"showCustomControls\",\n \"className\",\n \"style\",\n \"wrapperClassName\",\n \"wrapperStyle\",\n \"playsInline\",\n \"preload\",\n \"poster\",\n \"children\"\n ];\n for (const prop of uiProps) {\n if (prevProps[prop] !== nextProps[prop]) {\n return false;\n }\n }\n const callbackProps = [\n \"onReady\",\n \"onVolumeToggle\",\n \"onFullscreenToggle\",\n \"onControlClick\"\n ];\n for (const prop of callbackProps) {\n if (prevProps[prop] !== nextProps[prop]) {\n return false;\n }\n }\n return true;\n }\n);\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n StormcloudVideoPlayerComponent\n});\n","import React, { useEffect, useRef, useMemo, useCallback } from \"react\";\nimport { StormcloudVideoPlayer } from \"../player/StormcloudVideoPlayer\";\nimport type { StormcloudVideoPlayerConfig } from \"../types\";\nimport {\n FaPlay,\n FaPause,\n FaVolumeUp,\n FaVolumeMute,\n FaVolumeDown,\n FaExpand,\n FaCompress,\n} from \"react-icons/fa\";\n\nexport type StormcloudVideoPlayerProps = Omit<\n StormcloudVideoPlayerConfig,\n \"videoElement\"\n> &\n React.VideoHTMLAttributes<HTMLVideoElement> & {\n onReady?: (player: StormcloudVideoPlayer) => void;\n wrapperClassName?: string;\n wrapperStyle?: React.CSSProperties;\n licenseKey?: string;\n };\n\nconst CRITICAL_PROPS = [\n \"src\",\n \"allowNativeHls\",\n \"licenseKey\",\n \"vmapUrl\",\n \"lowLatencyMode\",\n \"driftToleranceMs\",\n \"vastMode\",\n] as const;\n\nconst CONTROLS_HIDE_DELAY = 3000;\nconst DEFAULT_PLAYER_ASPECT_RATIO = 16 / 9;\n\nexport const StormcloudVideoPlayerComponent: React.FC<StormcloudVideoPlayerProps> =\n React.memo(\n (props) => {\n const {\n src,\n autoplay,\n muted,\n lowLatencyMode,\n allowNativeHls,\n driftToleranceMs,\n immediateManifestAds,\n debugAdTiming,\n showCustomControls,\n hideLoadingIndicator,\n onVolumeToggle,\n onFullscreenToggle,\n onControlClick,\n onReady,\n wrapperClassName,\n wrapperStyle,\n className,\n style,\n controls,\n playsInline,\n preload,\n poster,\n children,\n licenseKey,\n vastMode,\n vastTagUrl,\n vmapUrl,\n minSegmentsBeforePlay,\n ...restVideoAttrs\n } = props;\n\n const videoRef = useRef<HTMLVideoElement | null>(null);\n const playerRef = useRef<StormcloudVideoPlayer | null>(null);\n const bufferingTimeoutRef = useRef<number | null>(null);\n const controlsTimerRef = useRef<number | null>(null);\n const wrapperRef = useRef<HTMLDivElement | null>(null);\n const [adStatus, setAdStatus] = React.useState<{\n showAds: boolean;\n currentIndex: number;\n totalAds: number;\n remainingSeconds: number;\n }>({ showAds: false, currentIndex: 0, totalAds: 0, remainingSeconds: 0 });\n\n const [shouldShowNativeControls, setShouldShowNativeControls] =\n React.useState(true);\n\n const [isMuted, setIsMuted] = React.useState(false);\n const [isFullscreen, setIsFullscreen] = React.useState(false);\n const [isPlaying, setIsPlaying] = React.useState(false);\n const [currentTime, setCurrentTime] = React.useState(0);\n const [duration, setDuration] = React.useState(0);\n const [volume, setVolume] = React.useState(1);\n const [playbackRate, setPlaybackRate] = React.useState(1);\n const [showVolumeSlider, setShowVolumeSlider] = React.useState(false);\n const [showSpeedMenu, setShowSpeedMenu] = React.useState(false);\n const [isLoading, setIsLoading] = React.useState(true);\n const [isBuffering, setIsBuffering] = React.useState(false);\n const [showCenterPlay, setShowCenterPlay] = React.useState(false);\n const [showLicenseWarning, setShowLicenseWarning] = React.useState(false);\n const [controlsVisible, setControlsVisible] = React.useState(true);\n const [viewportWidth, setViewportWidth] = React.useState(\n typeof window !== \"undefined\" ? window.innerWidth : 1920\n );\n const [isPortrait, setIsPortrait] = React.useState(\n typeof window !== \"undefined\"\n ? window.innerHeight > window.innerWidth\n : false\n );\n const [playerAspectRatio, setPlayerAspectRatio] = React.useState(\n DEFAULT_PLAYER_ASPECT_RATIO\n );\n\n const getResponsiveScale = () => {\n if (viewportWidth < 480) return 0.7;\n if (viewportWidth < 768) return 0.8;\n if (viewportWidth < 1024) return 0.9;\n return 1;\n };\n\n const responsiveScale = getResponsiveScale();\n\n const resetControlsTimer = useCallback(() => {\n if (controlsTimerRef.current) {\n clearTimeout(controlsTimerRef.current);\n }\n setControlsVisible(true);\n controlsTimerRef.current = window.setTimeout(() => {\n if (!showVolumeSlider && !showSpeedMenu) {\n setControlsVisible(false);\n }\n }, CONTROLS_HIDE_DELAY);\n }, [showVolumeSlider, showSpeedMenu]);\n\n const handleWrapperMouseMove = useCallback(() => {\n resetControlsTimer();\n }, [resetControlsTimer]);\n\n const handleWrapperMouseLeave = useCallback(() => {\n if (!showVolumeSlider && !showSpeedMenu) {\n setControlsVisible(false);\n }\n }, [showVolumeSlider, showSpeedMenu]);\n\n const formatTime = (seconds: number): string => {\n if (!isFinite(seconds)) return \"0:00:00\";\n const hours = Math.floor(seconds / 3600);\n const minutes = Math.floor((seconds % 3600) / 60);\n const remainingSeconds = Math.floor(seconds % 60);\n return `${hours}:${minutes\n .toString()\n .padStart(2, \"0\")}:${remainingSeconds.toString().padStart(2, \"0\")}`;\n };\n\n const handlePlayPause = () => {\n if (videoRef.current) {\n if (videoRef.current.paused) {\n const hasValidSource =\n videoRef.current.src ||\n (videoRef.current.currentSrc &&\n videoRef.current.currentSrc !== \"\") ||\n videoRef.current.readyState >= 1;\n\n if (hasValidSource) {\n videoRef.current.play()?.catch((error) => {\n console.error(\"[StormcloudVideoPlayer] Failed to play:\", error);\n });\n setShowCenterPlay(false);\n } else {\n console.warn(\n \"[StormcloudVideoPlayer] Cannot play: video has no valid source\"\n );\n }\n } else {\n videoRef.current.pause();\n setShowCenterPlay(true);\n }\n }\n resetControlsTimer();\n };\n\n const handleCenterPlayClick = () => {\n if (videoRef.current && videoRef.current.paused) {\n const hasValidSource =\n videoRef.current.src ||\n (videoRef.current.currentSrc &&\n videoRef.current.currentSrc !== \"\") ||\n videoRef.current.readyState >= 1;\n\n if (hasValidSource) {\n videoRef.current.play()?.catch((error) => {\n console.error(\"[StormcloudVideoPlayer] Failed to play:\", error);\n });\n setShowCenterPlay(false);\n } else {\n console.warn(\n \"[StormcloudVideoPlayer] Cannot play: video has no valid source\"\n );\n }\n }\n };\n\n const handleTimelineSeek = (e: React.MouseEvent<HTMLDivElement>) => {\n if (videoRef.current && duration > 0 && isFinite(duration)) {\n const rect = e.currentTarget.getBoundingClientRect();\n const clickX = e.clientX - rect.left;\n const progress = Math.max(0, Math.min(1, clickX / rect.width));\n const newTime = progress * duration;\n\n if (isFinite(newTime) && newTime >= 0 && newTime <= duration) {\n videoRef.current.currentTime = newTime;\n }\n }\n resetControlsTimer();\n };\n\n const handleVolumeChange = (newVolume: number) => {\n if (playerRef.current && isFinite(newVolume)) {\n const clampedVolume = Math.max(0, Math.min(1, newVolume));\n playerRef.current.setVolume(clampedVolume);\n }\n };\n\n const handlePlaybackRateChange = (rate: number) => {\n if (videoRef.current && isFinite(rate) && rate > 0) {\n videoRef.current.playbackRate = rate;\n }\n setShowSpeedMenu(false);\n };\n\n const isHlsStream =\n src?.toLowerCase().includes(\".m3u8\") ||\n src?.toLowerCase().includes(\"/hls/\");\n const shouldShowEnhancedControls =\n showCustomControls && (isHlsStream ? allowNativeHls : true);\n\n const criticalPropsKey = useMemo(() => {\n return CRITICAL_PROPS.map((prop) => `${prop}:${props[prop]}`).join(\"|\");\n }, [\n src,\n allowNativeHls,\n licenseKey,\n vmapUrl,\n lowLatencyMode,\n driftToleranceMs,\n vastMode,\n ]);\n\n useEffect(() => {\n if (typeof window === \"undefined\") return;\n const el = videoRef.current;\n if (!el || !src) return;\n\n if (!licenseKey) {\n setShowLicenseWarning(true);\n setIsLoading(false);\n console.warn(\n \"StormcloudVideoPlayer: License key is required but not provided. Please set the licenseKey prop to use the player.\"\n );\n return;\n }\n\n setShowLicenseWarning(false);\n\n if (debugAdTiming) {\n console.log(\"[StormcloudUI] Initializing player, isLoading=true\");\n }\n\n if (playerRef.current) {\n try {\n playerRef.current.destroy();\n } catch {}\n playerRef.current = null;\n }\n\n const cfg: StormcloudVideoPlayerConfig = {\n src,\n videoElement: el,\n } as StormcloudVideoPlayerConfig;\n if (autoplay !== undefined) cfg.autoplay = autoplay;\n if (muted !== undefined) cfg.muted = muted;\n if (lowLatencyMode !== undefined) cfg.lowLatencyMode = lowLatencyMode;\n if (allowNativeHls !== undefined) cfg.allowNativeHls = allowNativeHls;\n if (driftToleranceMs !== undefined)\n cfg.driftToleranceMs = driftToleranceMs;\n if (immediateManifestAds !== undefined)\n cfg.immediateManifestAds = immediateManifestAds;\n if (debugAdTiming !== undefined) cfg.debugAdTiming = debugAdTiming;\n if (showCustomControls !== undefined)\n cfg.showCustomControls = showCustomControls;\n if (onVolumeToggle !== undefined) cfg.onVolumeToggle = onVolumeToggle;\n if (onFullscreenToggle !== undefined)\n cfg.onFullscreenToggle = onFullscreenToggle;\n if (onControlClick !== undefined) cfg.onControlClick = onControlClick;\n if (licenseKey !== undefined) cfg.licenseKey = licenseKey;\n if (vastMode !== undefined) cfg.vastMode = vastMode;\n if (vastTagUrl !== undefined) cfg.vastTagUrl = vastTagUrl;\n if (vmapUrl !== undefined) cfg.vmapUrl = vmapUrl;\n if (minSegmentsBeforePlay !== undefined)\n cfg.minSegmentsBeforePlay = minSegmentsBeforePlay;\n\n const player = new StormcloudVideoPlayer(cfg);\n playerRef.current = player;\n player\n .load()\n .then(() => {\n const showNative = player.shouldShowNativeControls();\n setShouldShowNativeControls(showNative);\n if (debugAdTiming) {\n console.log(\n \"[StormcloudUI] Player loaded successfully, waiting for video ready\"\n );\n }\n onReady?.(player);\n })\n .catch((error) => {\n console.error(\n \"StormcloudVideoPlayer: Failed to load player:\",\n error\n );\n setIsLoading(false);\n onReady?.(player);\n });\n\n return () => {\n try {\n player.destroy();\n } catch {}\n playerRef.current = null;\n };\n }, [criticalPropsKey]);\n\n useEffect(() => {\n if (!playerRef.current) return;\n\n try {\n if (autoplay !== undefined && playerRef.current.videoElement) {\n playerRef.current.videoElement.autoplay = autoplay;\n }\n if (muted !== undefined && !playerRef.current.isShowingAds()) {\n playerRef.current.setMuted(muted);\n }\n } catch (error) {\n console.warn(\"Failed to update player properties:\", error);\n }\n }, [autoplay, muted]);\n\n useEffect(() => {\n if (!playerRef.current) return;\n\n const checkAdStatus = () => {\n if (playerRef.current) {\n const showAdsFromMethod = playerRef.current.isShowingAds();\n const showAdsFromAttribute = videoRef.current?.dataset?.stormcloudAdPlaying === \"true\";\n const showAds = showAdsFromMethod || showAdsFromAttribute;\n const currentIndex = playerRef.current.getCurrentAdIndex();\n const totalAds = playerRef.current.getTotalAdsInBreak();\n const remainingMs = playerRef.current.getAdRemainingMs();\n const remainingSeconds = showAds\n ? Math.max(0, Math.ceil(remainingMs / 1000))\n : 0;\n\n setAdStatus((prev) => {\n if (\n prev.showAds !== showAds ||\n prev.currentIndex !== currentIndex ||\n prev.totalAds !== totalAds ||\n prev.remainingSeconds !== remainingSeconds\n ) {\n if (showAds && !prev.showAds) {\n setShowCenterPlay(false);\n }\n return { showAds, currentIndex, totalAds, remainingSeconds };\n }\n return prev;\n });\n }\n };\n\n const interval = setInterval(checkAdStatus, 50);\n return () => clearInterval(interval);\n }, []);\n\n useEffect(() => {\n if (typeof window === \"undefined\" || !playerRef.current) return;\n\n const handleResize = () => {\n if (playerRef.current && videoRef.current) {\n if (typeof playerRef.current.resize === \"function\") {\n playerRef.current.resize();\n }\n }\n setViewportWidth(window.innerWidth);\n setIsPortrait(window.innerHeight > window.innerWidth);\n };\n\n window.addEventListener(\"resize\", handleResize);\n return () => window.removeEventListener(\"resize\", handleResize);\n }, []);\n\n useEffect(() => {\n if (!playerRef.current || !videoRef.current) return;\n\n const updateStates = () => {\n if (playerRef.current && videoRef.current) {\n setIsMuted(playerRef.current.isMuted());\n setIsPlaying(!videoRef.current.paused);\n\n const currentTimeValue = videoRef.current.currentTime;\n setCurrentTime(isFinite(currentTimeValue) ? currentTimeValue : 0);\n\n const durationValue = videoRef.current.duration;\n setDuration(isFinite(durationValue) ? durationValue : 0);\n\n const volumeValue = playerRef.current.getVolume();\n setVolume(\n isFinite(volumeValue) ? Math.max(0, Math.min(1, volumeValue)) : 1\n );\n\n const rateValue = videoRef.current.playbackRate;\n setPlaybackRate(\n isFinite(rateValue) && rateValue > 0 ? rateValue : 1\n );\n }\n setIsFullscreen(\n document.fullscreenElement === wrapperRef.current\n );\n };\n\n const interval = setInterval(updateStates, 200);\n\n const handleFullscreenChange = () => {\n setIsFullscreen(\n document.fullscreenElement === wrapperRef.current\n );\n };\n\n document.addEventListener(\"fullscreenchange\", handleFullscreenChange);\n\n return () => {\n clearInterval(interval);\n document.removeEventListener(\n \"fullscreenchange\",\n handleFullscreenChange\n );\n };\n }, []);\n\n useEffect(() => {\n if (!videoRef.current) return;\n\n const handleLoadedMetadata = () => {\n const video = videoRef.current;\n if (video) {\n if (video.videoWidth > 0 && video.videoHeight > 0) {\n setPlayerAspectRatio(video.videoWidth / video.videoHeight);\n }\n void video.offsetHeight;\n }\n if (debugAdTiming) {\n console.log(\n \"[StormcloudUI] Video event: loadedmetadata, readyState:\",\n videoRef.current?.readyState\n );\n }\n };\n\n const handleLoadedData = () => {\n if (debugAdTiming) {\n console.log(\n \"[StormcloudUI] Video event: loadeddata, readyState:\",\n videoRef.current?.readyState\n );\n }\n };\n\n const handleLoadStart = () => {\n if (debugAdTiming) {\n console.log(\n \"[StormcloudUI] Video event: loadstart, readyState:\",\n videoRef.current?.readyState\n );\n }\n };\n\n const handleCanPlay = () => {\n setIsLoading(false);\n if (bufferingTimeoutRef.current) {\n clearTimeout(bufferingTimeoutRef.current);\n bufferingTimeoutRef.current = null;\n }\n setIsBuffering(false);\n if (debugAdTiming) {\n console.log(\n \"[StormcloudUI] Video event: canplay, readyState:\",\n videoRef.current?.readyState,\n \"- clearing loading state, isLoading=false\"\n );\n }\n };\n\n const handleCanPlayThrough = () => {\n setIsLoading(false);\n if (bufferingTimeoutRef.current) {\n clearTimeout(bufferingTimeoutRef.current);\n bufferingTimeoutRef.current = null;\n }\n setIsBuffering(false);\n if (debugAdTiming) {\n console.log(\n \"[StormcloudUI] Video event: canplaythrough, readyState:\",\n videoRef.current?.readyState,\n \"- clearing loading state, isLoading=false\"\n );\n }\n };\n\n const handleWaiting = () => {\n if (bufferingTimeoutRef.current) {\n clearTimeout(bufferingTimeoutRef.current);\n }\n\n bufferingTimeoutRef.current = window.setTimeout(() => {\n setIsBuffering(true);\n if (debugAdTiming) {\n console.log(\n \"[StormcloudUI] Video buffering detected (after 300ms delay), readyState:\",\n videoRef.current?.readyState,\n \"- showing spinner, isBuffering=true\"\n );\n }\n }, 300);\n\n if (debugAdTiming) {\n console.log(\n \"[StormcloudUI] Video event: waiting, readyState:\",\n videoRef.current?.readyState,\n \"- buffering delay started (300ms)\"\n );\n }\n };\n\n const handlePlaying = () => {\n setIsLoading(false);\n if (bufferingTimeoutRef.current) {\n clearTimeout(bufferingTimeoutRef.current);\n bufferingTimeoutRef.current = null;\n }\n setIsBuffering(false);\n setShowCenterPlay(false);\n if (debugAdTiming) {\n console.log(\n \"[StormcloudUI] Video event: playing, readyState:\",\n videoRef.current?.readyState,\n \"- playback started, isLoading=false, isBuffering=false\"\n );\n }\n };\n\n const handlePause = () => {\n const isAdActive = playerRef.current?.isShowingAds() || \n videoRef.current?.dataset?.stormcloudAdPlaying === \"true\";\n \n if (playerRef.current && !isAdActive) {\n setShowCenterPlay(true);\n } else {\n setShowCenterPlay(false);\n }\n };\n\n const handleEnded = () => {\n setShowCenterPlay(true);\n };\n\n const video = videoRef.current;\n video.addEventListener(\"loadstart\", handleLoadStart);\n video.addEventListener(\"loadedmetadata\", handleLoadedMetadata);\n video.addEventListener(\"loadeddata\", handleLoadedData);\n video.addEventListener(\"canplay\", handleCanPlay);\n video.addEventListener(\"canplaythrough\", handleCanPlayThrough);\n video.addEventListener(\"waiting\", handleWaiting);\n video.addEventListener(\"playing\", handlePlaying);\n video.addEventListener(\"pause\", handlePause);\n video.addEventListener(\"ended\", handleEnded);\n\n if (video.paused) {\n setShowCenterPlay(true);\n }\n\n return () => {\n if (bufferingTimeoutRef.current) {\n clearTimeout(bufferingTimeoutRef.current);\n bufferingTimeoutRef.current = null;\n }\n\n video.removeEventListener(\"loadstart\", handleLoadStart);\n video.removeEventListener(\"loadedmetadata\", handleLoadedMetadata);\n video.removeEventListener(\"loadeddata\", handleLoadedData);\n video.removeEventListener(\"canplay\", handleCanPlay);\n video.removeEventListener(\"canplaythrough\", handleCanPlayThrough);\n video.removeEventListener(\"waiting\", handleWaiting);\n video.removeEventListener(\"playing\", handlePlaying);\n video.removeEventListener(\"pause\", handlePause);\n video.removeEventListener(\"ended\", handleEnded);\n };\n }, [debugAdTiming]);\n\n useEffect(() => {\n setPlayerAspectRatio(DEFAULT_PLAYER_ASPECT_RATIO);\n }, [src]);\n\n useEffect(() => {\n return () => {\n if (controlsTimerRef.current) {\n clearTimeout(controlsTimerRef.current);\n }\n };\n }, []);\n\n const progressPercent = duration > 0 ? (currentTime / duration) * 100 : 0;\n\n const VolumeIcon = isMuted || volume === 0\n ? FaVolumeMute\n : volume < 0.5\n ? FaVolumeDown\n : FaVolumeUp;\n\n return (\n <>\n <style>\n {`\n @keyframes sc-spin {\n from { transform: rotate(0deg); }\n to { transform: rotate(360deg); }\n }\n @keyframes sc-loading-glow {\n 0%, 100% { opacity: 0.85; transform: scale(1); }\n 50% { opacity: 1; transform: scale(1.05); }\n }\n @keyframes sc-pulse {\n 0%, 100% { opacity: 1; }\n 50% { opacity: 0.6; }\n }\n @keyframes sc-fade-in {\n from { opacity: 0; transform: translateY(8px); }\n to { opacity: 1; transform: translateY(0); }\n }\n .sc-wrapper:fullscreen,\n .sc-wrapper:has(*:fullscreen) {\n border-radius: 0 !important;\n box-shadow: none !important;\n width: 100vw !important;\n height: 100vh !important;\n max-width: 100vw !important;\n max-height: 100vh !important;\n position: fixed !important;\n top: 0 !important;\n left: 0 !important;\n z-index: 999999 !important;\n background: #000 !important;\n display: flex !important;\n align-items: center !important;\n justify-content: center !important;\n }\n .sc-ctrl-btn {\n background: none;\n border: none;\n color: #fff;\n cursor: pointer;\n display: flex;\n align-items: center;\n justify-content: center;\n border-radius: 50%;\n padding: 8px;\n transition: background 0.15s ease, opacity 0.15s ease;\n opacity: 0.9;\n }\n .sc-ctrl-btn:hover {\n opacity: 1;\n background: rgba(255, 255, 255, 0.1);\n }\n .sc-ctrl-btn:active {\n opacity: 0.7;\n }\n .sc-controls-bar {\n transition: opacity 0.35s ease, transform 0.35s ease;\n }\n .sc-progress-track:hover .sc-progress-thumb {\n transform: translate(-50%, -50%) scale(1) !important;\n }\n .sc-loading-hidden .sc-loading-indicator {\n display: none !important;\n }\n `}\n </style>\n <div\n ref={wrapperRef}\n className={`sc-wrapper ${wrapperClassName || \"\"}`}\n onMouseMove={handleWrapperMouseMove}\n onMouseLeave={handleWrapperMouseLeave}\n style={{\n display: \"flex\",\n alignItems: \"center\",\n justifyContent: \"center\",\n position: isFullscreen ? \"fixed\" : \"relative\",\n top: isFullscreen ? 0 : undefined,\n left: isFullscreen ? 0 : undefined,\n overflow: \"hidden\",\n width: isFullscreen ? \"100vw\" : \"100%\",\n height: isFullscreen ? \"100vh\" : \"auto\",\n minHeight: isFullscreen ? \"100vh\" : \"auto\",\n aspectRatio: isFullscreen ? undefined : playerAspectRatio,\n maxWidth: isFullscreen ? \"100vw\" : \"100%\",\n maxHeight: isFullscreen ? \"100vh\" : \"none\",\n zIndex: isFullscreen ? 999999 : undefined,\n backgroundColor: \"#000\",\n borderRadius: isFullscreen ? 0 : undefined,\n boxShadow: isFullscreen ? \"none\" : undefined,\n ...wrapperStyle,\n }}\n >\n <video\n ref={videoRef}\n className={className}\n style={{\n display: \"block\",\n width: \"100%\",\n height: \"100%\",\n maxWidth: \"100%\",\n maxHeight: isFullscreen ? \"100%\" : \"none\",\n objectFit: isFullscreen ? \"cover\" : \"contain\",\n backgroundColor: \"#000\",\n aspectRatio: isFullscreen ? \"unset\" : undefined,\n ...style,\n }}\n controls={\n shouldShowNativeControls && controls && !showCustomControls\n }\n playsInline={playsInline}\n preload={preload}\n poster={poster}\n {...restVideoAttrs}\n >\n {children}\n </video>\n\n {(isLoading || isBuffering) && !hideLoadingIndicator && (\n <div\n className=\"sc-loading-indicator\"\n style={{\n position: \"absolute\",\n top: \"50%\",\n left: \"50%\",\n transform: \"translate(-50%, -50%)\",\n zIndex: 20,\n width: `${Math.max(34, 38 * responsiveScale)}px`,\n height: `${Math.max(34, 38 * responsiveScale)}px`,\n display: \"flex\",\n alignItems: \"center\",\n justifyContent: \"center\",\n animation: \"sc-loading-glow 1.4s ease-in-out infinite\",\n filter: \"drop-shadow(0 6px 14px rgba(0, 0, 0, 0.55))\",\n }}\n >\n <div\n style={{\n position: \"absolute\",\n inset: 0,\n borderRadius: \"50%\",\n border: \"3px solid rgba(255, 255, 255, 0.25)\",\n borderTopColor: \"#ff0000\",\n borderRightColor: \"rgba(255, 255, 255, 0.85)\",\n animation: \"sc-spin 0.8s linear infinite\",\n }}\n />\n <div\n style={{\n width: \"7px\",\n height: \"7px\",\n borderRadius: \"50%\",\n background: \"#ff0000\",\n boxShadow: \"0 0 10px rgba(255, 0, 0, 0.65)\",\n }}\n />\n </div>\n )}\n\n {showLicenseWarning && (\n <div\n style={{\n position: \"absolute\",\n top: \"50%\",\n left: \"50%\",\n transform: \"translate(-50%, -50%)\",\n zIndex: 25,\n background: \"rgba(220, 38, 38, 0.92)\",\n backdropFilter: \"blur(24px)\",\n color: \"white\",\n padding: \"28px 36px\",\n borderRadius: \"14px\",\n border: \"1px solid rgba(255, 255, 255, 0.15)\",\n boxShadow: \"0 24px 64px rgba(0, 0, 0, 0.5)\",\n textAlign: \"center\",\n maxWidth: \"400px\",\n margin: \"0 16px\",\n }}\n >\n <div style={{ fontSize: \"18px\", fontWeight: \"700\", marginBottom: \"10px\", letterSpacing: \"-0.02em\" }}>\n License Key Required\n </div>\n <div style={{ fontSize: \"13px\", lineHeight: \"1.6\", color: \"rgba(255, 255, 255, 0.85)\" }}>\n Please provide a valid license key to use the Stormcloud Video\n Player.\n <br />\n Contact your administrator for licensing information.\n </div>\n </div>\n )}\n\n {adStatus.showAds && (\n <div\n style={{\n position: \"absolute\",\n top: `${12 * responsiveScale}px`,\n left: `${12 * responsiveScale}px`,\n zIndex: 50,\n display: \"flex\",\n alignItems: \"center\",\n gap: \"8px\",\n pointerEvents: \"none\",\n animation: \"sc-fade-in 0.3s ease\",\n }}\n >\n <div\n style={{\n background: \"rgba(234, 179, 8, 0.95)\",\n color: \"#111\",\n padding: `${4 * responsiveScale}px ${12 * responsiveScale}px`,\n borderRadius: \"6px\",\n fontSize: `${11 * responsiveScale}px`,\n fontWeight: 700,\n letterSpacing: \"0.08em\",\n textTransform: \"uppercase\" as const,\n boxShadow: \"0 2px 12px rgba(234, 179, 8, 0.35)\",\n }}\n >\n Ad\n </div>\n <div\n style={{\n background: \"rgba(0, 0, 0, 0.58)\",\n color: \"rgba(255, 255, 255, 0.92)\",\n padding: `${4 * responsiveScale}px ${10 * responsiveScale}px`,\n borderRadius: \"6px\",\n fontSize: `${11 * responsiveScale}px`,\n fontWeight: 600,\n border: \"1px solid rgba(255, 255, 255, 0.1)\",\n boxShadow: \"0 2px 10px rgba(0, 0, 0, 0.25)\",\n }}\n >\n {`${Math.max(1, adStatus.currentIndex)} of ${Math.max(\n Math.max(1, adStatus.currentIndex),\n adStatus.totalAds\n )}`}\n </div>\n </div>\n )}\n\n {showCenterPlay &&\n !isLoading &&\n !isBuffering &&\n !showLicenseWarning &&\n !adStatus.showAds && (\n <div\n onClick={handleCenterPlayClick}\n style={{\n position: \"absolute\",\n top: \"50%\",\n left: \"50%\",\n transform: \"translate(-50%, -50%)\",\n zIndex: 15,\n cursor: \"pointer\",\n background: \"rgba(0, 0, 0, 0.55)\",\n backdropFilter: \"blur(8px)\",\n borderRadius: \"50%\",\n width: `${92 * responsiveScale}px`,\n height: `${92 * responsiveScale}px`,\n display: \"flex\",\n alignItems: \"center\",\n justifyContent: \"center\",\n transition: \"background 0.2s ease, transform 0.2s ease\",\n animation: \"sc-fade-in 0.2s ease\",\n }}\n onMouseEnter={(e) => {\n (e.currentTarget as HTMLElement).style.background = \"rgba(0, 0, 0, 0.72)\";\n (e.currentTarget as HTMLElement).style.transform = \"translate(-50%, -50%) scale(1.06)\";\n }}\n onMouseLeave={(e) => {\n (e.currentTarget as HTMLElement).style.background = \"rgba(0, 0, 0, 0.55)\";\n (e.currentTarget as HTMLElement).style.transform = \"translate(-50%, -50%) scale(1)\";\n }}\n title=\"Play\"\n >\n <FaPlay\n size={Math.max(24, 32 * responsiveScale)}\n color=\"white\"\n style={{ marginLeft: \"4px\" }}\n />\n </div>\n )}\n\n {shouldShowEnhancedControls && !showLicenseWarning ? (\n <div\n className=\"sc-controls-bar\"\n style={{\n position: \"absolute\",\n bottom: 0,\n left: 0,\n right: 0,\n background: \"linear-gradient(0deg, rgba(0, 0, 0, 0.8) 0%, rgba(0, 0, 0, 0.35) 60%, transparent 100%)\",\n padding: `${20 * responsiveScale}px ${12 * responsiveScale}px ${8 * responsiveScale}px`,\n zIndex: 10,\n opacity: controlsVisible || adStatus.showAds ? 1 : 0,\n transform: controlsVisible || adStatus.showAds ? \"translateY(0)\" : \"translateY(6px)\",\n pointerEvents: controlsVisible || adStatus.showAds ? \"auto\" : \"none\",\n }}\n >\n {/* Progress Bar */}\n <div\n className=\"sc-progress-track\"\n style={{\n width: \"100%\",\n height: \"3px\",\n background: \"rgba(255, 255, 255, 0.2)\",\n borderRadius: \"1.5px\",\n marginBottom: `${8 * responsiveScale}px`,\n cursor: \"pointer\",\n position: \"relative\",\n transition: \"height 0.1s ease\",\n }}\n onClick={handleTimelineSeek}\n onMouseEnter={(e) => { e.currentTarget.style.height = \"5px\"; }}\n onMouseLeave={(e) => { e.currentTarget.style.height = \"3px\"; }}\n >\n <div\n style={{\n position: \"absolute\",\n top: 0, left: 0, bottom: 0,\n background: adStatus.showAds ? \"#f5c518\" : \"#ff0000\",\n borderRadius: \"1.5px\",\n width: `${progressPercent}%`,\n transition: \"width 0.15s linear\",\n }}\n />\n <div\n className=\"sc-progress-thumb\"\n style={{\n position: \"absolute\",\n top: \"50%\",\n left: `${progressPercent}%`,\n transform: \"translate(-50%, -50%) scale(0)\",\n width: \"13px\",\n height: \"13px\",\n background: adStatus.showAds ? \"#f5c518\" : \"#ff0000\",\n borderRadius: \"50%\",\n boxShadow: \"0 0 4px rgba(0, 0, 0, 0.3)\",\n transition: \"transform 0.1s ease, left 0.15s linear\",\n }}\n />\n </div>\n\n {/* Controls Row */}\n <div\n style={{\n display: \"flex\",\n alignItems: \"center\",\n justifyContent: \"space-between\",\n color: \"white\",\n gap: `${8 * responsiveScale}px`,\n }}\n >\n {/* Left Group */}\n <div\n style={{\n display: \"flex\",\n alignItems: \"center\",\n gap: `${8 * responsiveScale}px`,\n }}\n >\n {/* Play/Pause */}\n <button\n className=\"sc-ctrl-btn\"\n onClick={handlePlayPause}\n style={{\n padding: `${8 * responsiveScale}px`,\n borderRadius: \"50%\",\n minWidth: `${36 * responsiveScale}px`,\n minHeight: `${36 * responsiveScale}px`,\n }}\n title={isPlaying ? \"Pause\" : \"Play\"}\n >\n {isPlaying ? (\n <FaPause size={Math.max(14, 18 * responsiveScale)} />\n ) : (\n <FaPlay size={Math.max(14, 18 * responsiveScale)} style={{ marginLeft: \"2px\" }} />\n )}\n </button>\n\n {/* Volume Group - YouTube Style */}\n <div\n style={{\n display: \"flex\",\n alignItems: \"center\",\n paddingRight: `${6 * responsiveScale}px`,\n }}\n onMouseEnter={() => setShowVolumeSlider(true)}\n onMouseLeave={() => setShowVolumeSlider(false)}\n >\n <button\n className=\"sc-ctrl-btn\"\n onClick={() => {\n if (playerRef.current) playerRef.current.toggleMute();\n onVolumeToggle?.();\n resetControlsTimer();\n }}\n style={{\n padding: `${8 * responsiveScale}px`,\n borderRadius: \"50%\",\n minWidth: `${36 * responsiveScale}px`,\n minHeight: `${36 * responsiveScale}px`,\n }}\n title={isMuted ? \"Unmute\" : \"Mute\"}\n >\n <VolumeIcon size={Math.max(14, 18 * responsiveScale)} />\n </button>\n <div\n style={{\n width: showVolumeSlider ? `${68 * responsiveScale}px` : \"0px\",\n overflow: \"hidden\",\n transition: \"width 0.2s cubic-bezier(0.4, 0, 0.2, 1)\",\n display: \"flex\",\n alignItems: \"center\",\n paddingLeft: showVolumeSlider ? `${3 * responsiveScale}px` : \"0\",\n paddingRight: showVolumeSlider ? `${8 * responsiveScale}px` : \"0\",\n }}\n >\n <div\n style={{\n position: \"relative\",\n width: `${56 * responsiveScale}px`,\n height: \"3px\",\n cursor: \"pointer\",\n borderRadius: \"1.5px\",\n }}\n onMouseDown={(e) => {\n e.preventDefault();\n const el = e.currentTarget;\n const move = (ev: MouseEvent) => {\n const r = el.getBoundingClientRect();\n handleVolumeChange(Math.max(0, Math.min(1, (ev.clientX - r.left) / r.width)));\n };\n const up = () => { document.removeEventListener(\"mousemove\", move); document.removeEventListener(\"mouseup\", up); };\n document.addEventListener(\"mousemove\", move);\n document.addEventListener(\"mouseup\", up);\n const r = el.getBoundingClientRect();\n handleVolumeChange(Math.max(0, Math.min(1, (e.clientX - r.left) / r.width)));\n }}\n onClick={(e) => {\n e.stopPropagation();\n const r = e.currentTarget.getBoundingClientRect();\n handleVolumeChange(Math.max(0, Math.min(1, (e.clientX - r.left) / r.width)));\n }}\n >\n <div style={{ position: \"absolute\", inset: 0, background: \"rgba(255, 255, 255, 0.2)\", borderRadius: \"1.5px\" }} />\n <div\n style={{\n position: \"absolute\",\n top: 0, left: 0, bottom: 0,\n width: `${(isMuted ? 0 : volume) * 100}%`,\n background: \"#fff\",\n borderRadius: \"1.5px\",\n transition: \"width 0.1s ease-out\",\n }}\n />\n <div\n style={{\n position: \"absolute\",\n top: \"50%\",\n left: `${(isMuted ? 0 : volume) * 100}%`,\n transform: \"translate(-50%, -50%)\",\n width: \"12px\",\n height: \"12px\",\n background: \"#fff\",\n borderRadius: \"50%\",\n boxShadow: \"0 0 3px rgba(0, 0, 0, 0.3)\",\n transition: \"left 0.1s ease-out\",\n }}\n />\n </div>\n </div>\n </div>\n\n {/* Time Display */}\n <div\n style={{\n fontSize: `${13 * responsiveScale}px`,\n fontFamily: \"Roboto, 'Segoe UI', Arial, sans-serif\",\n color: \"rgba(255, 255, 255, 0.9)\",\n display: viewportWidth < 480 ? \"none\" : \"block\",\n fontVariantNumeric: \"tabular-nums\",\n userSelect: \"none\",\n marginLeft: `${4 * responsiveScale}px`,\n }}\n >\n {formatTime(currentTime)}{\" \"}\n <span style={{ color: \"rgba(255,255,255,0.5)\" }}>/</span>{\" \"}\n {formatTime(duration)}\n </div>\n </div>\n\n {/* Right Group */}\n <div\n style={{\n display: \"flex\",\n alignItems: \"center\",\n gap: `${8 * responsiveScale}px`,\n }}\n >\n {/* Speed Selector */}\n <div style={{ position: \"relative\", display: viewportWidth < 600 ? \"none\" : \"block\" }}>\n <button\n className=\"sc-ctrl-btn\"\n onClick={() => { setShowSpeedMenu(!showSpeedMenu); resetControlsTimer(); }}\n style={{\n padding: `${6 * responsiveScale}px ${10 * responsiveScale}px`,\n borderRadius: `${6 * responsiveScale}px`,\n fontSize: `${13 * responsiveScale}px`,\n fontFamily: \"'SF Mono', 'Cascadia Code', monospace\",\n fontWeight: \"600\",\n minHeight: `${32 * responsiveScale}px`,\n }}\n title=\"Playback Speed\"\n >\n {playbackRate}x\n </button>\n\n {showSpeedMenu && (\n <div\n style={{\n position: \"absolute\",\n bottom: \"100%\",\n right: 0,\n marginBottom: \"8px\",\n background: \"rgba(0, 0, 0, 0.8)\",\n backdropFilter: \"blur(24px)\",\n WebkitBackdropFilter: \"blur(24px)\",\n borderRadius: \"10px\",\n border: \"1px solid rgba(255, 255, 255, 0.1)\",\n overflow: \"hidden\",\n minWidth: \"80px\",\n boxShadow: \"0 12px 40px rgba(0, 0, 0, 0.5)\",\n animation: \"sc-fade-in 0.15s ease\",\n }}\n >\n {[0.25, 0.5, 0.75, 1, 1.25, 1.5, 1.75, 2].map((speed) => (\n <button\n key={speed}\n onClick={() => handlePlaybackRateChange(speed)}\n style={{\n display: \"block\",\n width: \"100%\",\n padding: `${8 * responsiveScale}px ${14 * responsiveScale}px`,\n background: playbackRate === speed\n ? \"rgba(255, 255, 255, 0.12)\"\n : \"transparent\",\n border: \"none\",\n color: playbackRate === speed ? \"#fff\" : \"rgba(255, 255, 255, 0.7)\",\n cursor: \"pointer\",\n fontSize: `${12 * responsiveScale}px`,\n fontFamily: \"'SF Mono', monospace\",\n fontWeight: playbackRate === speed ? \"700\" : \"500\",\n textAlign: \"center\",\n transition: \"background 0.15s ease, color 0.15s ease\",\n }}\n onMouseEnter={(e) => {\n if (playbackRate !== speed) {\n (e.target as HTMLElement).style.background = \"rgba(255, 255, 255, 0.08)\";\n (e.target as HTMLElement).style.color = \"#fff\";\n }\n }}\n onMouseLeave={(e) => {\n if (playbackRate !== speed) {\n (e.target as HTMLElement).style.background = \"transparent\";\n (e.target as HTMLElement).style.color = \"rgba(255, 255, 255, 0.7)\";\n }\n }}\n >\n {speed}x\n </button>\n ))}\n </div>\n )}\n </div>\n\n {/* Fullscreen */}\n <button\n className=\"sc-ctrl-btn\"\n onClick={() => {\n if (onFullscreenToggle) {\n onFullscreenToggle();\n } else if (wrapperRef.current) {\n if (!document.fullscreenElement) {\n wrapperRef.current.requestFullscreen().catch(() => {});\n } else {\n document.exitFullscreen().catch(() => {});\n }\n }\n resetControlsTimer();\n }}\n style={{\n padding: `${8 * responsiveScale}px`,\n borderRadius: \"50%\",\n minWidth: `${36 * responsiveScale}px`,\n minHeight: `${36 * responsiveScale}px`,\n }}\n title={isFullscreen ? \"Exit Fullscreen\" : \"Enter Fullscreen\"}\n >\n {isFullscreen ? (\n <FaCompress size={Math.max(14, 18 * responsiveScale)} />\n ) : (\n <FaExpand size={Math.max(14, 18 * responsiveScale)} />\n )}\n </button>\n </div>\n </div>\n </div>\n ) : (\n showCustomControls && !showLicenseWarning && (\n <div\n className=\"sc-controls-bar\"\n style={{\n position: \"absolute\",\n bottom: `${10 * responsiveScale}px`,\n right: `${10 * responsiveScale}px`,\n display: \"flex\",\n flexDirection: isPortrait ? \"column\" : \"row\",\n gap: `${8 * responsiveScale}px`,\n zIndex: 10,\n opacity: controlsVisible ? 1 : 0,\n transform: controlsVisible ? \"translateY(0)\" : \"translateY(4px)\",\n pointerEvents: controlsVisible ? \"auto\" : \"none\",\n }}\n >\n <div\n style={{\n display: \"flex\",\n alignItems: \"center\",\n background: \"rgba(0, 0, 0, 0.6)\",\n borderRadius: `${18 * responsiveScale}px`,\n padding: \"2px\",\n paddingRight: `${8 * responsiveScale}px`,\n }}\n onMouseEnter={() => setShowVolumeSlider(true)}\n onMouseLeave={() => setShowVolumeSlider(false)}\n >\n <button\n className=\"sc-ctrl-btn\"\n onClick={() => {\n if (playerRef.current) playerRef.current.toggleMute();\n onVolumeToggle?.();\n resetControlsTimer();\n }}\n style={{\n padding: `${8 * responsiveScale}px`,\n borderRadius: \"50%\",\n minWidth: `${36 * responsiveScale}px`,\n minHeight: `${36 * responsiveScale}px`,\n }}\n title={isMuted ? \"Unmute\" : \"Mute\"}\n >\n <VolumeIcon size={Math.max(14, 18 * responsiveScale)} />\n </button>\n <div\n style={{\n width: showVolumeSlider ? `${68 * responsiveScale}px` : \"0px\",\n overflow: \"hidden\",\n transition: \"width 0.2s cubic-bezier(0.4, 0, 0.2, 1)\",\n display: \"flex\",\n alignItems: \"center\",\n paddingLeft: showVolumeSlider ? `${3 * responsiveScale}px` : \"0\",\n paddingRight: showVolumeSlider ? `${10 * responsiveScale}px` : \"0\",\n }}\n >\n <div\n style={{\n position: \"relative\",\n width: `${56 * responsiveScale}px`,\n height: \"3px\",\n cursor: \"pointer\",\n borderRadius: \"1.5px\",\n }}\n onMouseDown={(e) => {\n e.preventDefault();\n const el = e.currentTarget;\n const move = (ev: MouseEvent) => {\n const r = el.getBoundingClientRect();\n handleVolumeChange(Math.max(0, Math.min(1, (ev.clientX - r.left) / r.width)));\n };\n const up = () => { document.removeEventListener(\"mousemove\", move); document.removeEventListener(\"mouseup\", up); };\n document.addEventListener(\"mousemove\", move);\n document.addEventListener(\"mouseup\", up);\n const r = el.getBoundingClientRect();\n handleVolumeChange(Math.max(0, Math.min(1, (e.clientX - r.left) / r.width)));\n }}\n onClick={(e) => {\n e.stopPropagation();\n const r = e.currentTarget.getBoundingClientRect();\n handleVolumeChange(Math.max(0, Math.min(1, (e.clientX - r.left) / r.width)));\n }}\n >\n <div style={{ position: \"absolute\", inset: 0, background: \"rgba(255, 255, 255, 0.2)\", borderRadius: \"1.5px\" }} />\n <div\n style={{\n position: \"absolute\",\n top: 0, left: 0, bottom: 0,\n width: `${(isMuted ? 0 : volume) * 100}%`,\n background: \"#fff\",\n borderRadius: \"1.5px\",\n transition: \"width 0.1s ease-out\",\n }}\n />\n <div\n style={{\n position: \"absolute\",\n top: \"50%\",\n left: `${(isMuted ? 0 : volume) * 100}%`,\n transform: \"translate(-50%, -50%)\",\n width: \"12px\",\n height: \"12px\",\n background: \"#fff\",\n borderRadius: \"50%\",\n boxShadow: \"0 0 3px rgba(0, 0, 0, 0.3)\",\n transition: \"left 0.1s ease-out\",\n }}\n />\n </div>\n </div>\n </div>\n\n <button\n className=\"sc-ctrl-btn\"\n onClick={() => {\n if (onFullscreenToggle) {\n onFullscreenToggle();\n } else if (wrapperRef.current) {\n if (!document.fullscreenElement) {\n wrapperRef.current.requestFullscreen().catch(() => {});\n } else {\n document.exitFullscreen().catch(() => {});\n }\n }\n resetControlsTimer();\n }}\n style={{\n padding: `${8 * responsiveScale}px`,\n borderRadius: \"50%\",\n minWidth: `${36 * responsiveScale}px`,\n minHeight: `${36 * responsiveScale}px`,\n background: \"rgba(0, 0, 0, 0.6)\",\n }}\n title={isFullscreen ? \"Exit Fullscreen\" : \"Enter Fullscreen\"}\n >\n {isFullscreen ? (\n <FaCompress size={Math.max(14, 18 * responsiveScale)} />\n ) : (\n <FaExpand size={Math.max(14, 18 * responsiveScale)} />\n )}\n </button>\n </div>\n )\n )}\n\n {onControlClick && (\n <div\n onClick={onControlClick}\n style={{\n position: \"absolute\",\n top: 0,\n left: 0,\n right: 0,\n bottom: 0,\n zIndex: 1,\n cursor: \"pointer\",\n }}\n />\n )}\n </div>\n </>\n );\n },\n (prevProps, nextProps) => {\n for (const prop of CRITICAL_PROPS) {\n if ((prevProps as any)[prop] !== (nextProps as any)[prop]) {\n return false;\n }\n }\n\n const uiProps = [\n \"autoplay\",\n \"muted\",\n \"controls\",\n \"showCustomControls\",\n \"className\",\n \"style\",\n \"wrapperClassName\",\n \"wrapperStyle\",\n \"playsInline\",\n \"preload\",\n \"poster\",\n \"children\",\n ] as const;\n\n for (const prop of uiProps) {\n if ((prevProps as any)[prop] !== (nextProps as any)[prop]) {\n return false;\n }\n }\n\n const callbackProps = [\n \"onReady\",\n \"onVolumeToggle\",\n \"onFullscreenToggle\",\n \"onControlClick\",\n ] as const;\n for (const prop of callbackProps) {\n if ((prevProps as any)[prop] !== (nextProps as any)[prop]) {\n return false;\n }\n }\n\n return true;\n }\n );\n","import Hls from \"hls.js\";\nimport type {\n StormcloudVideoPlayerConfig,\n Scte35Marker,\n Id3TagInfo,\n AdController,\n AdBreak,\n StormcloudApiResponse,\n} from \"../types\";\nimport { createHlsAdPlayer } from \"../sdk/hlsAdPlayer\";\nimport { createPalNonceManager } from \"../sdk/pal\";\nimport type { PalNonceManager } from \"../sdk/pal\";\nimport {\n sendInitialTracking,\n sendHeartbeat,\n sendAdDetectTracking,\n sendAdLoadedTracking,\n sendAdImpressionTracking,\n} from \"../utils/tracking\";\nimport { initializePolyfills } from \"../utils/polyfills\";\nimport {\n logBrowserInfo,\n getBrowserConfigOverrides,\n} from \"../utils/browserCompat\";\n\ntype Scte35CueSource = \"manifest\" | \"id3\" | \"ts\";\ntype Scte35CueReadiness = \"early\" | \"playback\";\n\ninterface NormalizedScte35Cue {\n marker: Scte35Marker;\n source: Scte35CueSource;\n readiness: Scte35CueReadiness;\n key: string;\n fragmentSn?: number;\n fragmentStartSeconds?: number;\n}\n\ninterface Scte35CueContext {\n source: Scte35CueSource;\n readiness: Scte35CueReadiness;\n fragmentSn?: number;\n fragmentStartSeconds?: number;\n}\n\nexport class StormcloudVideoPlayer {\n private readonly video: HTMLVideoElement;\n private readonly config: StormcloudVideoPlayerConfig;\n private hls?: Hls;\n private adPlayer: AdController;\n private attached = false;\n private inAdBreak = false;\n private currentAdBreakStartWallClockMs: number | undefined;\n private expectedAdBreakDurationMs: number | undefined;\n private adStopTimerId: number | undefined;\n private adStartTimerId: number | undefined;\n private adFailsafeTimerId: number | undefined;\n private ptsDriftEmaMs = 0;\n private adPodQueue: string[] = [];\n private apiVastTagUrl: string | undefined;\n private apiNumberAds: number | undefined;\n private vmapBreaks: AdBreak[] = [];\n private consumedVmapBreakIds: Set<string> = new Set();\n private lastHeartbeatTime: number = 0;\n private heartbeatInterval: number | undefined;\n private currentAdIndex: number = 0;\n private totalAdsInBreak: number = 0;\n private showAds: boolean = false;\n private isLiveStream: boolean = false;\n private nativeHlsMode: boolean = false;\n private videoSrcProtection: string | null = null;\n private bufferedSegmentsCount: number = 0;\n private shouldAutoplayAfterBuffering: boolean = false;\n private hasInitialBufferCompleted: boolean = false;\n private adRequestTokenCounter = 0;\n private activeAdRequestToken: number | null = null;\n private adRequestWatchdogId: number | undefined;\n private adRequestWatchdogToken: number | null = null;\n private adFailsafeToken: number | null = null;\n private failedVastUrls: Set<string> = new Set();\n private temporaryFailureUrls: Map<string, number> = new Map();\n private readonly temporaryFailureCooldownMs: number = 30000;\n private continuousFetchingActive: boolean = false;\n private adRequestQueue: string[] = [];\n private maxPlaceholderDurationMs: number = 5000;\n private isShowingPlaceholder: boolean = false;\n private timeUpdateHandler?: (event: Event) => void;\n private emptiedHandler?: (event: Event) => void;\n private readonly tsScte35Pids: Set<number> = new Set();\n private readonly pmtPids: Set<number> = new Set();\n private readonly processedTsScte35Sections: Set<string> = new Set();\n private readonly pendingScte35Cues: Map<string, NormalizedScte35Cue> =\n new Map();\n private readonly recentScte35CueKeys: Map<string, number> = new Map();\n private readonly recentScte35CueLimit: number = 200;\n private pendingScte35CueKey: string | undefined;\n private activeScte35BreakKey: string | undefined;\n private scheduledScte35BreakKey: string | undefined;\n \n private totalAdRequestsInBreak: number = 0;\n private readonly maxTotalAdRequestsPerBreak: number = 10;\n \n private pendingAdBreak: {\n marker: Scte35Marker;\n detectedAtFragmentSn?: number;\n vastUrls: string[];\n isFetching: boolean;\n fetchStartTime?: number;\n } | null = null;\n private prefetchTimerId: number | undefined;\n \n private consecutiveFailures: number = 0;\n private readonly maxConsecutiveFailures: number = 5;\n private lastAdRequestTime: number = 0;\n private readonly minAdRequestIntervalMs: number = 3000;\n private readonly backoffBaseMs: number = 1000;\n private readonly maxBackoffMs: number = 15000;\n private placeholderContainer: HTMLDivElement | undefined;\n\n private globalConsecutiveNoFills: number = 0;\n private readonly globalNoFillThreshold: number = 3;\n private globalNoFillCooldownUntil: number = 0;\n private readonly globalNoFillBackoffBaseMs: number = 5000;\n private readonly globalNoFillBackoffMaxMs: number = 60000;\n private globalLastGamRequestTime: number = 0;\n private readonly globalMinGamIntervalMs: number = 3000;\n\n private preloadPool: Array<{\n vastUrl: string;\n adController: AdController;\n loadedAt: number;\n isReady: boolean;\n loadPromise: Promise<void>;\n }> = [];\n private readonly maxPreloadPoolSize: number = 2;\n private preloadPoolActive: boolean = false;\n private preloadPoolLoopRunning: boolean = false;\n private adDetectSentForCurrentBreak: boolean = false;\n\n private palNonce: PalNonceManager;\n private palPlaybackStarted: boolean = false;\n\n constructor(config: StormcloudVideoPlayerConfig) {\n initializePolyfills();\n\n const browserOverrides = getBrowserConfigOverrides();\n \n this.config = { ...browserOverrides, ...config };\n this.video = config.videoElement;\n\n logBrowserInfo(config.debugAdTiming);\n\n this.adPlayer = this.createAdPlayer(false);\n this.palNonce = createPalNonceManager();\n }\n\n private createAdPlayer(continueLiveStreamDuringAds: boolean): AdController {\n if (this.config.debugAdTiming) {\n console.log(\"[StormcloudVideoPlayer] Creating HLS ad player\");\n }\n return createHlsAdPlayer(this.video, {\n continueLiveStreamDuringAds,\n ...(this.config.licenseKey\n ? { licenseKey: this.config.licenseKey }\n : {}),\n ...(this.hls ? { mainHlsInstance: this.hls } : {}),\n });\n }\n\n async load(): Promise<void> {\n if (!this.attached) {\n this.attach();\n }\n\n try {\n await this.fetchAdConfiguration();\n } catch (error) {\n if (this.config.debugAdTiming) {\n console.warn(\n \"[StormcloudVideoPlayer] Failed to fetch ad configuration:\",\n error\n );\n }\n }\n\n // Generate a PAL nonce for this stream session. The nonce is appended to\n // all VAST URLs as `givn` to unlock AdX demand without the IMA SDK.\n this.palNonce.generateNonce({\n videoWidth: this.video.offsetWidth || this.video.clientWidth || 640,\n videoHeight: this.video.offsetHeight || this.video.clientHeight || 480,\n adWillAutoPlay: !!this.config.autoplay,\n adWillPlayMuted: !!this.config.muted,\n continuousPlayback: this.config.lowLatencyMode ?? false,\n }).catch(() => {});\n\n this.initializeTracking();\n\n if (this.shouldUseNativeHls()) {\n this.nativeHlsMode = true;\n this.videoSrcProtection = this.config.src;\n this.video.src = this.config.src;\n\n this.isLiveStream = this.config.lowLatencyMode ?? false;\n\n if (this.config.debugAdTiming) {\n console.log(\n \"[StormcloudVideoPlayer] Using native HLS playback - VOD mode:\",\n {\n isLive: this.isLiveStream,\n allowNativeHls: this.config.allowNativeHls,\n adBehavior: \"vod (main video pauses during ads)\",\n }\n );\n }\n\n this.adPlayer.destroy();\n this.adPlayer = this.createAdPlayer(false);\n this.adPlayer.initialize();\n\n if (this.config.autoplay) {\n await this.video.play()?.catch(() => {});\n }\n return;\n }\n\n this.hls = new Hls({\n enableWorker: true,\n backBufferLength: 30,\n liveDurationInfinity: true,\n lowLatencyMode: !!this.config.lowLatencyMode,\n maxLiveSyncPlaybackRate: this.config.lowLatencyMode ? 1.5 : 1.0,\n ...(this.config.lowLatencyMode ? { liveSyncDuration: 2 } : {}),\n maxBufferLength: 30,\n maxMaxBufferLength: 600,\n maxBufferSize: 60 * 1000 * 1000,\n maxBufferHole: 0.5,\n highBufferWatchdogPeriod: 2,\n nudgeOffset: 0.1,\n nudgeMaxRetry: 3,\n startPosition: -1,\n });\n\n this.hls.on(Hls.Events.MEDIA_ATTACHED, () => {\n this.hls?.loadSource(this.config.src);\n });\n\n this.hls.on(Hls.Events.MANIFEST_PARSED, async (_, data: any) => {\n if (this.config.allowNativeHls === false) {\n this.isLiveStream = true;\n } else {\n this.isLiveStream =\n this.hls?.levels?.some(\n (level) =>\n level?.details?.live === true || level?.details?.type === \"LIVE\"\n ) ?? false;\n }\n\n if (this.config.debugAdTiming) {\n const adBehavior = this.shouldContinueLiveStreamDuringAds()\n ? \"live (main video continues muted during ads)\"\n : \"vod (main video pauses during ads)\";\n console.log(\"[StormcloudVideoPlayer] Stream type detected:\", {\n isLive: this.isLiveStream,\n allowNativeHls: this.config.allowNativeHls,\n adBehavior,\n });\n }\n\n this.adPlayer.destroy();\n this.adPlayer = this.createAdPlayer(this.shouldContinueLiveStreamDuringAds());\n this.adPlayer.initialize();\n\n this.bufferedSegmentsCount = 0;\n this.hasInitialBufferCompleted = false;\n this.shouldAutoplayAfterBuffering = !!this.config.autoplay;\n\n const minSegments = this.config.minSegmentsBeforePlay ?? 2;\n\n if (this.config.debugAdTiming) {\n console.log(\n \"[StormcloudVideoPlayer] Waiting for\",\n minSegments,\n \"segments to buffer before playback\"\n );\n }\n\n if (minSegments === 0 || !this.config.autoplay) {\n this.hasInitialBufferCompleted = true;\n if (this.config.autoplay) {\n await this.video.play()?.catch(() => {});\n }\n }\n });\n\n this.hls.on(Hls.Events.LEVEL_LOADED, (_evt, data: any) => {\n if (this.inAdBreak || this.pendingAdBreak) {\n return;\n }\n\n const details = data?.details;\n if (!details || !details.fragments || details.fragments.length === 0) {\n return;\n }\n\n const fragmentsToScan = Math.min(5, details.fragments.length);\n \n for (let i = 0; i < fragmentsToScan; i++) {\n const frag = details.fragments[i];\n const tagList: any[] | undefined = frag?.tagList;\n \n if (!Array.isArray(tagList)) continue;\n\n for (const entry of tagList) {\n let tag = \"\";\n let value = \"\";\n \n if (Array.isArray(entry)) {\n tag = String(entry[0] ?? \"\");\n value = String(entry[1] ?? \"\");\n } else if (typeof entry === \"string\") {\n const idx = entry.indexOf(\":\");\n if (idx >= 0) {\n tag = entry.substring(0, idx);\n value = entry.substring(idx + 1);\n } else {\n tag = entry;\n }\n }\n\n if (!tag) continue;\n\n if (tag.includes(\"EXT-X-CUE-OUT\") || tag.includes(\"EXT-X-DATERANGE\")) {\n const attrs = tag.includes(\"EXT-X-DATERANGE\") \n ? this.parseAttributeList(value)\n : {};\n const hasScteOut = tag.includes(\"EXT-X-CUE-OUT\") || \n \"SCTE35-OUT\" in attrs || \n attrs[\"SCTE35-OUT\"] !== undefined;\n\n if (hasScteOut) {\n const durationSeconds = this.parseCueOutDuration(value);\n const marker: Scte35Marker = {\n type: \"start\",\n ...(durationSeconds !== undefined ? { durationSeconds } : {}),\n raw: { tag, value, earlyDetection: true },\n } as Scte35Marker;\n\n if (this.config.debugAdTiming) {\n console.log(\"[StormcloudVideoPlayer] 🎯 EARLY SCTE-35 DETECTION: Ad break marker found in fragment\", i, \"- starting pre-fetch (NOT playing yet)\");\n }\n\n this.onScte35Cue(marker, {\n ...this.createScte35CueContext(\"manifest\", \"early\", frag),\n });\n return;\n }\n }\n }\n }\n });\n\n this.hls.on(Hls.Events.FRAG_BUFFERED, async (_evt, data: any) => {\n if (this.hasInitialBufferCompleted) {\n return;\n }\n\n this.bufferedSegmentsCount++;\n const minSegments = this.config.minSegmentsBeforePlay ?? 2;\n\n if (this.config.debugAdTiming) {\n console.log(\n `[StormcloudVideoPlayer] Buffered segment ${this.bufferedSegmentsCount}/${minSegments}`\n );\n }\n\n if (this.bufferedSegmentsCount >= minSegments) {\n this.hasInitialBufferCompleted = true;\n\n if (this.shouldAutoplayAfterBuffering) {\n if (this.config.debugAdTiming) {\n console.log(\n `[StormcloudVideoPlayer] Initial buffer complete (${this.bufferedSegmentsCount} segments). Starting playback.`\n );\n }\n await this.video.play()?.catch((err) => {\n if (this.config.debugAdTiming) {\n console.warn(\"[StormcloudVideoPlayer] Autoplay failed:\", err);\n }\n });\n }\n }\n });\n\n this.hls.on(Hls.Events.FRAG_PARSING_METADATA, (_evt, data: any) => {\n const id3Tags: Id3TagInfo[] = (data?.samples || []).map((s: any) => ({\n key: \"ID3\",\n value: s?.data,\n ptsSeconds: s?.pts,\n }));\n id3Tags.forEach((tag) => this.onId3Tag(tag));\n });\n\n this.hls.on(Hls.Events.FRAG_LOADED, (_evt, data: any) => {\n this.processFragmentScte35Payload(\n data?.payload,\n typeof data?.frag?.sn === \"number\" ? data.frag.sn : undefined,\n this.getFragmentStartSeconds(data?.frag)\n );\n });\n\n this.hls.on(Hls.Events.FRAG_DECRYPTED, (_evt, data: any) => {\n this.processFragmentScte35Payload(\n data?.payload,\n typeof data?.frag?.sn === \"number\" ? data.frag.sn : undefined,\n this.getFragmentStartSeconds(data?.frag)\n );\n });\n\n this.hls.on(Hls.Events.FRAG_CHANGED, (_evt, data: any) => {\n const frag = data?.frag;\n const tagList: any[] | undefined = frag?.tagList;\n if (!Array.isArray(tagList)) {\n this.activatePendingScte35CuesForFragment(frag);\n return;\n }\n\n for (const entry of tagList) {\n let tag = \"\";\n let value = \"\";\n if (Array.isArray(entry)) {\n tag = String(entry[0] ?? \"\");\n value = String(entry[1] ?? \"\");\n } else if (typeof entry === \"string\") {\n const idx = entry.indexOf(\":\");\n if (idx >= 0) {\n tag = entry.substring(0, idx);\n value = entry.substring(idx + 1);\n } else {\n tag = entry;\n value = \"\";\n }\n }\n\n if (!tag) continue;\n if (tag.includes(\"EXT-X-CUE-OUT-CONT\")) {\n const prog = this.parseCueOutCont(value);\n const marker: Scte35Marker = {\n type: \"progress\",\n ...(prog?.duration !== undefined\n ? { durationSeconds: prog.duration }\n : {}),\n ...(prog?.elapsed !== undefined\n ? { ptsSeconds: prog.elapsed }\n : {}),\n raw: { tag, value },\n } as Scte35Marker;\n this.onScte35Cue(marker, {\n ...this.createScte35CueContext(\"manifest\", \"playback\", frag),\n });\n } else if (tag.includes(\"EXT-X-CUE-OUT\")) {\n const durationSeconds = this.parseCueOutDuration(value);\n const marker: Scte35Marker = {\n type: \"start\",\n ...(durationSeconds !== undefined ? { durationSeconds } : {}),\n raw: { tag, value },\n } as Scte35Marker;\n this.onScte35Cue(marker, {\n ...this.createScte35CueContext(\"manifest\", \"playback\", frag),\n });\n } else if (tag.includes(\"EXT-X-CUE-IN\")) {\n this.onScte35Cue(\n { type: \"end\", raw: { tag, value } },\n {\n ...this.createScte35CueContext(\"manifest\", \"playback\", frag),\n }\n );\n } else if (tag.includes(\"EXT-X-DATERANGE\")) {\n const attrs = this.parseAttributeList(value);\n const hasScteOut =\n \"SCTE35-OUT\" in attrs || attrs[\"SCTE35-OUT\"] !== undefined;\n const hasScteIn =\n \"SCTE35-IN\" in attrs || attrs[\"SCTE35-IN\"] !== undefined;\n const klass = String(attrs[\"CLASS\"] ?? \"\");\n const duration = this.toNumber(attrs[\"DURATION\"]);\n\n if (hasScteOut || /com\\.apple\\.hls\\.cue/i.test(klass)) {\n const marker: Scte35Marker = {\n type: \"start\",\n ...(duration !== undefined ? { durationSeconds: duration } : {}),\n raw: { tag, value, attrs },\n } as Scte35Marker;\n this.onScte35Cue(marker, {\n ...this.createScte35CueContext(\"manifest\", \"playback\", frag),\n });\n }\n if (hasScteIn) {\n this.onScte35Cue(\n { type: \"end\", raw: { tag, value, attrs } },\n {\n ...this.createScte35CueContext(\"manifest\", \"playback\", frag),\n }\n );\n }\n }\n }\n this.activatePendingScte35CuesForFragment(frag);\n });\n\n this.hls.on(Hls.Events.ERROR, (_evt, data) => {\n if (data?.fatal) {\n switch (data.type) {\n case Hls.ErrorTypes.NETWORK_ERROR:\n this.hls?.startLoad();\n break;\n case Hls.ErrorTypes.MEDIA_ERROR:\n this.hls?.recoverMediaError();\n break;\n default:\n this.destroy();\n break;\n }\n }\n });\n\n this.hls.attachMedia(this.video);\n }\n\n private attachImaEventListeners(): void {\n this.adPlayer.on(\"all_ads_completed\", () => {\n sendAdImpressionTracking(\n this.config.licenseKey,\n { source: \"hls\", adIndex: this.currentAdIndex, timestamp: new Date().toISOString() }\n ).catch(() => {});\n\n const remaining = this.getRemainingAdMs();\n \n this.consecutiveFailures = 0;\n \n if (this.config.debugAdTiming) {\n console.log(\n `[StormcloudVideoPlayer] all_ads_completed event received - remaining=${remaining}ms, queued ads=${this.adRequestQueue.length}`,\n this.adRequestQueue.length > 0 ? { queuedUrls: [...this.adRequestQueue] } : {}\n );\n }\n\n if (this.inAdBreak) {\n if (remaining > 500) {\n this.tryNextAvailableAdWithRateLimit();\n } else {\n this.handleAdPodComplete();\n }\n }\n });\n this.adPlayer.on(\"ad_error\", (errorPayload?: any) => {\n let errorMessage = \"Ad playback failed\";\n \n if (errorPayload) {\n const errorCode = errorPayload.code || errorPayload.errorCode || \"unknown\";\n const vastErrorCode = errorPayload.vastErrorCode;\n const message = errorPayload.message || errorPayload.errorMessage || \"Unknown error\";\n const cause = errorPayload.cause || errorPayload.innerError || errorPayload.error;\n \n errorMessage = `Ad error: AdError ${errorCode}: ${message}`;\n \n if (vastErrorCode && vastErrorCode !== \"N/A\" && vastErrorCode !== errorCode) {\n errorMessage += ` (VAST Error Code: ${vastErrorCode})`;\n }\n \n if (cause) {\n const causeMessage = typeof cause === \"string\" ? cause : (cause.message || String(cause));\n errorMessage += `. Caused by: ${causeMessage}`;\n }\n }\n \n console.error(\"[AD-ERROR]\", errorMessage, errorPayload || \"\");\n this.handleAdFailure();\n });\n this.adPlayer.on(\"content_pause\", () => {\n this.clearAdFailsafeTimer();\n this.clearAdRequestWatchdog();\n this.activeAdRequestToken = null;\n this.showAds = true;\n this.resetGamNoFillCounter();\n \n if (this.inAdBreak && this.expectedAdBreakDurationMs != null && this.adStopTimerId == null) {\n this.scheduleAdStopCountdown(this.getRemainingAdMs());\n if (this.config.debugAdTiming) {\n console.log(\"[StormcloudVideoPlayer] Starting ad break timer on content_pause (first ad starting)\");\n }\n }\n \n const currentMuted = this.video.muted;\n const currentVolume = this.video.volume;\n const adVolume = currentMuted ? 0 : currentVolume;\n this.adPlayer.setAdVolume(adVolume);\n \n if (this.isShowingPlaceholder) {\n if (this.config.debugAdTiming) {\n console.log(\"[StormcloudVideoPlayer] Hiding placeholder - new ads starting\");\n }\n this.adPlayer.hidePlaceholder();\n this.isShowingPlaceholder = false;\n }\n });\n this.adPlayer.on(\"content_resume\", () => {\n sendAdImpressionTracking(\n this.config.licenseKey,\n { source: \"hls\", adIndex: this.currentAdIndex, timestamp: new Date().toISOString() }\n ).catch(() => {});\n\n if (!this.video.muted) {\n this.video.muted = true;\n this.video.volume = 0;\n if (this.config.debugAdTiming) {\n console.log(\"[StormcloudVideoPlayer] Muted video on content_resume (ad ended, gap between ads)\");\n }\n }\n\n this.clearAdFailsafeTimer();\n this.clearAdRequestWatchdog();\n this.activeAdRequestToken = null;\n this.showAds = false;\n\n if (!this.inAdBreak) {\n return;\n }\n\n this.consecutiveFailures = 0;\n\n const remaining = this.getRemainingAdMs();\n \n if (this.config.debugAdTiming) {\n console.log(\n `[CONTINUOUS-FETCH] content_resume event: remaining=${remaining}ms, queued ads=${this.adRequestQueue.length}`,\n this.adRequestQueue.length > 0 ? { queuedUrls: [...this.adRequestQueue] } : {}\n );\n }\n\n if (remaining > 500) {\n this.tryNextAvailableAdWithRateLimit();\n } else {\n this.handleAdPodComplete();\n }\n });\n }\n\n private recreateAdController(): void {\n if (this.config.debugAdTiming) {\n console.log(\"[StormcloudVideoPlayer] Recreating AdController for new ad\");\n }\n\n const shouldShowPlaceholder = this.inAdBreak && this.showAds;\n if (shouldShowPlaceholder && this.adPlayer) {\n if (this.config.debugAdTiming) {\n console.log(\"[StormcloudVideoPlayer] Showing placeholder before destroying old AdController\");\n }\n this.showPlaceholderLayer();\n this.adPlayer.showPlaceholder();\n this.isShowingPlaceholder = true;\n }\n\n const preservedMutedState = this.adPlayer.getOriginalMutedState();\n const preservedVolumeState = this.adPlayer.getOriginalVolume();\n\n if (this.adPlayer) {\n try {\n this.adPlayer.destroy();\n this.video.muted = true;\n this.video.volume = 0;\n } catch (error) {\n if (this.config.debugAdTiming) {\n console.warn(\"[StormcloudVideoPlayer] Error destroying old AdController:\", error);\n }\n }\n }\n\n const continueLiveStreamDuringAds = this.shouldContinueLiveStreamDuringAds();\n this.adPlayer = this.createAdPlayer(continueLiveStreamDuringAds);\n \n this.adPlayer.initialize();\n this.adPlayer.updateOriginalMutedState(preservedMutedState, preservedVolumeState);\n this.attachImaEventListeners();\n\n if (shouldShowPlaceholder) {\n this.showPlaceholderLayer();\n this.adPlayer.showPlaceholder();\n this.isShowingPlaceholder = true;\n }\n }\n\n private ensurePlaceholderContainer(): void {\n if (this.placeholderContainer) {\n return;\n }\n\n const container = document.createElement(\"div\");\n container.style.position = \"absolute\";\n container.style.left = \"0\";\n container.style.top = \"0\";\n container.style.right = \"0\";\n container.style.bottom = \"0\";\n container.style.display = \"none\";\n container.style.alignItems = \"center\";\n container.style.justifyContent = \"center\";\n container.style.pointerEvents = \"none\";\n container.style.zIndex = \"5\";\n container.style.backgroundColor = \"#000\";\n container.style.transition = \"opacity 0.3s ease-in-out\";\n container.style.opacity = \"0\";\n\n if (!this.video.parentElement) {\n if (this.config.debugAdTiming) {\n console.warn(\"[StormcloudVideoPlayer] Video element has no parent for placeholder container\");\n }\n return;\n }\n\n this.video.parentElement.appendChild(container);\n this.placeholderContainer = container;\n }\n\n private showPlaceholderLayer(): void {\n this.ensurePlaceholderContainer();\n \n if (!this.placeholderContainer) {\n return;\n }\n\n if (!this.video.muted) {\n this.video.muted = true;\n this.video.volume = 0;\n if (this.config.debugAdTiming) {\n console.log(\"[StormcloudVideoPlayer] Muted video when showing placeholder\");\n }\n }\n\n const wasHidden = this.placeholderContainer.style.display === \"none\" || this.placeholderContainer.style.opacity === \"0\";\n if (wasHidden) {\n this.placeholderContainer.style.transition = \"none\";\n } else {\n this.placeholderContainer.style.transition = \"opacity 0.3s ease-in-out\";\n }\n \n this.placeholderContainer.style.backgroundColor = \"#000\";\n this.placeholderContainer.style.display = \"flex\";\n this.placeholderContainer.offsetHeight;\n this.placeholderContainer.style.opacity = \"1\";\n this.placeholderContainer.style.pointerEvents = \"auto\";\n \n if (wasHidden) {\n requestAnimationFrame(() => {\n if (this.placeholderContainer) {\n this.placeholderContainer.style.transition = \"opacity 0.3s ease-in-out\";\n }\n });\n }\n\n if (this.config.debugAdTiming) {\n console.log(\"[StormcloudVideoPlayer] Showing placeholder layer (between content and ad layer)\");\n }\n }\n\n private hidePlaceholderLayer(): void {\n if (!this.placeholderContainer) {\n return;\n }\n\n this.placeholderContainer.style.opacity = \"0\";\n setTimeout(() => {\n if (this.placeholderContainer) {\n this.placeholderContainer.style.display = \"none\";\n this.placeholderContainer.style.pointerEvents = \"none\";\n this.placeholderContainer.style.backgroundColor = \"#000\";\n }\n }, 300);\n\n if (this.config.debugAdTiming) {\n console.log(\"[StormcloudVideoPlayer] Hiding placeholder layer\");\n }\n }\n\n private attach(): void {\n if (this.attached) return;\n this.attached = true;\n this.video.autoplay = !!this.config.autoplay;\n this.video.muted = !!this.config.muted;\n\n this.adPlayer.initialize();\n this.adPlayer.updateOriginalMutedState(this.video.muted, this.video.volume);\n this.attachImaEventListeners();\n\n this.video.addEventListener(\"play\", () => {\n if (!this.palPlaybackStarted && !this.adPlayer.isAdPlaying()) {\n this.palPlaybackStarted = true;\n this.palNonce.sendPlaybackStart();\n }\n });\n\n this.video.addEventListener(\"ended\", () => {\n if (this.palPlaybackStarted) {\n this.palPlaybackStarted = false;\n this.palNonce.sendPlaybackEnd();\n }\n });\n\n this.video.addEventListener(\"mousedown\", (e) => {\n this.palNonce.sendAdTouch(e as MouseEvent);\n });\n\n this.video.addEventListener(\"touchstart\", (e) => {\n this.palNonce.sendAdTouch(e as TouchEvent);\n });\n\n this.timeUpdateHandler = () => {\n this.onTimeUpdate(this.video.currentTime);\n };\n this.video.addEventListener(\"timeupdate\", this.timeUpdateHandler);\n\n this.emptiedHandler = () => {\n if (\n this.nativeHlsMode &&\n this.videoSrcProtection &&\n !this.adPlayer.isAdPlaying()\n ) {\n if (this.config.debugAdTiming) {\n console.log(\n \"[StormcloudVideoPlayer] Video src was cleared, restoring:\",\n this.videoSrcProtection\n );\n }\n const currentTime = this.video.currentTime;\n const wasPaused = this.video.paused;\n this.video.src = this.videoSrcProtection;\n this.video.currentTime = currentTime;\n if (!wasPaused) {\n this.video.play().catch(() => {});\n }\n }\n };\n this.video.addEventListener(\"emptied\", this.emptiedHandler);\n }\n\n private shouldUseNativeHls(): boolean {\n const streamType = this.getStreamType();\n\n if (streamType === \"other\") {\n return true;\n }\n\n const canNative = this.video.canPlayType(\"application/vnd.apple.mpegurl\");\n return !!(this.config.allowNativeHls && canNative);\n }\n\n private onId3Tag(tag: Id3TagInfo): void {\n if (typeof tag.ptsSeconds === \"number\") {\n this.updatePtsDrift(tag.ptsSeconds);\n }\n const marker = this.parseScte35FromId3(tag);\n if (marker) {\n this.onScte35Cue(marker, {\n source: \"id3\",\n readiness: \"playback\",\n });\n }\n }\n\n private parseScte35FromId3(tag: Id3TagInfo): Scte35Marker | undefined {\n const text = this.decodeId3ValueToText(tag.value);\n if (!text) return undefined;\n\n const cueOutMatch =\n text.match(/EXT-X-CUE-OUT(?::([^\\r\\n]*))?/i) ||\n text.match(/CUE-OUT(?::([^\\r\\n]*))?/i);\n if (cueOutMatch) {\n const arg = (cueOutMatch[1] ?? \"\").trim();\n const dur = this.parseCueOutDuration(arg);\n const marker: Scte35Marker = {\n type: \"start\",\n ...(tag.ptsSeconds !== undefined ? { ptsSeconds: tag.ptsSeconds } : {}),\n ...(dur !== undefined ? { durationSeconds: dur } : {}),\n raw: { id3: text },\n } as Scte35Marker;\n return marker;\n }\n\n const cueOutContMatch = text.match(/EXT-X-CUE-OUT-CONT:([^\\r\\n]*)/i);\n if (cueOutContMatch) {\n const arg = (cueOutContMatch[1] ?? \"\").trim();\n const cont = this.parseCueOutCont(arg);\n const marker: Scte35Marker = {\n type: \"progress\",\n ...(tag.ptsSeconds !== undefined ? { ptsSeconds: tag.ptsSeconds } : {}),\n ...(cont?.duration !== undefined\n ? { durationSeconds: cont.duration }\n : {}),\n raw: { id3: text },\n } as Scte35Marker;\n return marker;\n }\n\n const cueInMatch = text.match(/EXT-X-CUE-IN\\b/i) || text.match(/CUE-IN\\b/i);\n if (cueInMatch) {\n const marker: Scte35Marker = {\n type: \"end\",\n ...(tag.ptsSeconds !== undefined ? { ptsSeconds: tag.ptsSeconds } : {}),\n raw: { id3: text },\n } as Scte35Marker;\n return marker;\n }\n\n const daterangeMatch = text.match(/EXT-X-DATERANGE:([^\\r\\n]*)/i);\n if (daterangeMatch) {\n const attrs = this.parseAttributeList(daterangeMatch[1] ?? \"\");\n const hasScteOut =\n \"SCTE35-OUT\" in attrs || attrs[\"SCTE35-OUT\"] !== undefined;\n const hasScteIn =\n \"SCTE35-IN\" in attrs || attrs[\"SCTE35-IN\"] !== undefined;\n const klass = String(attrs[\"CLASS\"] ?? \"\");\n const duration = this.toNumber(attrs[\"DURATION\"]);\n if (hasScteOut || /com\\.apple\\.hls\\.cue/i.test(klass)) {\n const marker: Scte35Marker = {\n type: \"start\",\n ...(tag.ptsSeconds !== undefined\n ? { ptsSeconds: tag.ptsSeconds }\n : {}),\n ...(duration !== undefined ? { durationSeconds: duration } : {}),\n raw: { id3: text, attrs },\n } as Scte35Marker;\n return marker;\n }\n if (hasScteIn) {\n const marker: Scte35Marker = {\n type: \"end\",\n ...(tag.ptsSeconds !== undefined\n ? { ptsSeconds: tag.ptsSeconds }\n : {}),\n raw: { id3: text, attrs },\n } as Scte35Marker;\n return marker;\n }\n }\n\n if (/SCTE35-OUT/i.test(text)) {\n const marker: Scte35Marker = {\n type: \"start\",\n ...(tag.ptsSeconds !== undefined ? { ptsSeconds: tag.ptsSeconds } : {}),\n raw: { id3: text },\n } as Scte35Marker;\n return marker;\n }\n if (/SCTE35-IN/i.test(text)) {\n const marker: Scte35Marker = {\n type: \"end\",\n ...(tag.ptsSeconds !== undefined ? { ptsSeconds: tag.ptsSeconds } : {}),\n raw: { id3: text },\n } as Scte35Marker;\n return marker;\n }\n\n if (tag.value instanceof Uint8Array) {\n const bin = this.parseScte35Binary(tag.value);\n if (bin) return bin;\n }\n\n return undefined;\n }\n\n private decodeId3ValueToText(value: string | Uint8Array): string | undefined {\n try {\n if (typeof value === \"string\") return value;\n const decoder = new TextDecoder(\"utf-8\", { fatal: false });\n const text = decoder.decode(value);\n if (text && /[\\x20-\\x7E]/.test(text)) return text;\n let out = \"\";\n for (let i = 0; i < value.length; i++)\n out += String.fromCharCode(value[i]!);\n return out;\n } catch {\n return undefined;\n }\n }\n\n private createScte35CueContext(\n source: Scte35CueSource,\n readiness: Scte35CueReadiness,\n frag?: any\n ): Scte35CueContext {\n const context: Scte35CueContext = { source, readiness };\n if (typeof frag?.sn === \"number\") {\n context.fragmentSn = frag.sn;\n }\n const fragmentStartSeconds = this.getFragmentStartSeconds(frag);\n if (fragmentStartSeconds !== undefined) {\n context.fragmentStartSeconds = fragmentStartSeconds;\n }\n return context;\n }\n\n private getFragmentStartSeconds(frag: any): number | undefined {\n const candidates = [frag?.start, frag?.startPTS];\n for (const candidate of candidates) {\n if (typeof candidate === \"number\" && Number.isFinite(candidate)) {\n return candidate;\n }\n }\n return undefined;\n }\n\n private onScte35Cue(marker: Scte35Marker, context: Scte35CueContext): void {\n const cue = this.createScte35Cue(marker, context);\n const pendingKey = this.getPendingScte35CueKey(cue);\n\n if (context.readiness === \"early\") {\n this.pendingScte35Cues.set(pendingKey, cue);\n this.trimRecentScte35CueMaps();\n\n if (marker.type === \"start\") {\n this.startAdPrefetch(marker, context.fragmentSn, cue.key);\n }\n return;\n }\n\n if (marker.type === \"end\" && !this.shouldAcceptScte35EndCue(cue)) {\n if (this.config.debugAdTiming) {\n console.log(\"[StormcloudVideoPlayer] Ignoring SCTE-35 end cue\", {\n key: cue.key,\n activeScte35BreakKey: this.activeScte35BreakKey,\n inAdBreak: this.inAdBreak,\n source: cue.source,\n });\n }\n return;\n }\n\n if (marker.type === \"start\" && this.hasRecentlyHandledScte35Cue(cue)) {\n if (this.config.debugAdTiming) {\n console.log(\"[StormcloudVideoPlayer] Ignoring duplicate SCTE-35 start cue\", {\n key: cue.key,\n source: cue.source,\n });\n }\n return;\n }\n\n this.pendingScte35Cues.delete(pendingKey);\n this.markScte35CueHandled(cue);\n this.onScte35Marker(marker, cue.key);\n }\n\n private createScte35Cue(\n marker: Scte35Marker,\n context: Scte35CueContext\n ): NormalizedScte35Cue {\n const cue: NormalizedScte35Cue = {\n marker,\n source: context.source,\n readiness: context.readiness,\n key: this.getScte35CueKey(marker, context),\n };\n if (context.fragmentSn !== undefined) {\n cue.fragmentSn = context.fragmentSn;\n }\n if (context.fragmentStartSeconds !== undefined) {\n cue.fragmentStartSeconds = context.fragmentStartSeconds;\n }\n return cue;\n }\n\n private getScte35CueKey(\n marker: Scte35Marker,\n context: Scte35CueContext\n ): string {\n const raw = this.getScte35MarkerRaw(marker);\n const spliceEventId = this.toIdentityString(raw?.splice_event_id);\n if (spliceEventId) {\n return `splice:${spliceEventId}`;\n }\n\n const segmentationEventId = this.toIdentityString(raw?.segmentation_event_id);\n if (segmentationEventId) {\n return `segmentation:${segmentationEventId}`;\n }\n\n const daterangeId = this.toIdentityString(raw?.attrs?.ID);\n if (daterangeId) {\n return `daterange:${daterangeId}`;\n }\n\n const scteValue =\n this.toIdentityString(raw?.attrs?.[\"SCTE35-OUT\"]) ||\n this.toIdentityString(raw?.attrs?.[\"SCTE35-IN\"]);\n if (scteValue) {\n return `daterange-scte:${scteValue}`;\n }\n\n if (typeof marker.ptsSeconds === \"number\" && Number.isFinite(marker.ptsSeconds)) {\n return `pts:${Math.round(marker.ptsSeconds * 2) / 2}`;\n }\n\n if (context.fragmentSn !== undefined) {\n return `fragment:${context.fragmentSn}`;\n }\n\n return `${context.source}:wallclock:${Math.floor(Date.now() / 1000)}`;\n }\n\n private getPendingScte35CueKey(cue: NormalizedScte35Cue): string {\n return `${cue.marker.type}:${cue.key}:${\n cue.fragmentSn !== undefined ? cue.fragmentSn : \"unknown\"\n }`;\n }\n\n private getScte35MarkerRaw(marker: Scte35Marker): any {\n return typeof marker.raw === \"object\" && marker.raw !== null\n ? (marker.raw as any)\n : {};\n }\n\n private toIdentityString(value: unknown): string | undefined {\n if (typeof value === \"number\" && Number.isFinite(value)) {\n return String(value);\n }\n if (typeof value === \"string\" && value.trim().length > 0) {\n return value.trim();\n }\n return undefined;\n }\n\n private isStrongScte35CueKey(key: string | undefined): boolean {\n return !!(\n key &&\n (key.startsWith(\"splice:\") ||\n key.startsWith(\"segmentation:\") ||\n key.startsWith(\"daterange:\") ||\n key.startsWith(\"daterange-scte:\"))\n );\n }\n\n private hasRecentlyHandledScte35Cue(cue: NormalizedScte35Cue): boolean {\n if (\n this.activeScte35BreakKey === cue.key ||\n this.scheduledScte35BreakKey === cue.key\n ) {\n return true;\n }\n\n const recentKey = `${cue.marker.type}:${cue.key}`;\n return this.recentScte35CueKeys.has(recentKey);\n }\n\n private markScte35CueHandled(cue: NormalizedScte35Cue): void {\n this.recentScte35CueKeys.set(`${cue.marker.type}:${cue.key}`, Date.now());\n this.trimRecentScte35CueMaps();\n }\n\n private trimRecentScte35CueMaps(): void {\n while (this.recentScte35CueKeys.size > this.recentScte35CueLimit) {\n const firstKey = this.recentScte35CueKeys.keys().next().value;\n if (!firstKey) {\n break;\n }\n this.recentScte35CueKeys.delete(firstKey);\n }\n\n while (this.pendingScte35Cues.size > this.recentScte35CueLimit) {\n const firstKey = this.pendingScte35Cues.keys().next().value;\n if (!firstKey) {\n break;\n }\n this.pendingScte35Cues.delete(firstKey);\n }\n }\n\n private shouldAcceptScte35EndCue(cue: NormalizedScte35Cue): boolean {\n if (!this.inAdBreak) {\n return false;\n }\n\n if (\n this.isStrongScte35CueKey(this.activeScte35BreakKey) &&\n this.isStrongScte35CueKey(cue.key) &&\n this.activeScte35BreakKey !== cue.key\n ) {\n return false;\n }\n\n return true;\n }\n\n private activatePendingScte35CuesForFragment(frag: any): void {\n const fragmentSn = typeof frag?.sn === \"number\" ? frag.sn : undefined;\n if (fragmentSn === undefined) {\n return;\n }\n\n const matchingCues = Array.from(this.pendingScte35Cues.entries()).filter(\n ([, cue]) => cue.fragmentSn === fragmentSn\n );\n\n matchingCues.forEach(([pendingKey, cue]) => {\n this.pendingScte35Cues.delete(pendingKey);\n const context: Scte35CueContext = {\n source: cue.source,\n readiness: \"playback\",\n };\n context.fragmentSn = fragmentSn;\n const fragmentStartSeconds =\n cue.fragmentStartSeconds ?? this.getFragmentStartSeconds(frag);\n if (fragmentStartSeconds !== undefined) {\n context.fragmentStartSeconds = fragmentStartSeconds;\n }\n this.onScte35Cue(cue.marker, context);\n });\n }\n\n private onScte35Marker(marker: Scte35Marker, cueKey?: string): void {\n if (this.config.debugAdTiming) {\n console.log(\"[StormcloudVideoPlayer] SCTE-35 marker detected:\", {\n type: marker.type,\n ptsSeconds: marker.ptsSeconds,\n durationSeconds: marker.durationSeconds,\n currentTime: this.video.currentTime,\n raw: marker.raw,\n hasPendingAdBreak: !!this.pendingAdBreak,\n });\n }\n\n if (marker.type === \"start\") {\n if (this.inAdBreak) {\n if (marker.durationSeconds != null) {\n const newDurationMs = marker.durationSeconds * 1000;\n if (this.expectedAdBreakDurationMs == null || newDurationMs > this.expectedAdBreakDurationMs) {\n this.expectedAdBreakDurationMs = newDurationMs;\n const elapsedMs = this.currentAdBreakStartWallClockMs != null\n ? Date.now() - this.currentAdBreakStartWallClockMs\n : 0;\n const remainingMs = Math.max(0, newDurationMs - elapsedMs);\n this.scheduleAdStopCountdown(remainingMs);\n if (this.config.debugAdTiming) {\n console.log(\n `[StormcloudVideoPlayer] Updated ad break duration from subsequent marker: ${newDurationMs}ms, remaining: ${remainingMs}ms`\n );\n }\n }\n }\n return;\n }\n\n if (!this.adDetectSentForCurrentBreak) {\n this.adDetectSentForCurrentBreak = true;\n const detectPayload: {\n durationSeconds?: number;\n ptsSeconds?: number;\n detectedAtFragmentSn?: number;\n } = {};\n if (marker.durationSeconds != null) detectPayload.durationSeconds = marker.durationSeconds;\n if (marker.ptsSeconds != null) detectPayload.ptsSeconds = marker.ptsSeconds;\n sendAdDetectTracking(this.config.licenseKey, { source: \"scte35\", timestamp: new Date().toISOString(), ...detectPayload }).catch(() => {});\n }\n\n const hasPrefetchedAds = this.pendingAdBreak && this.pendingAdBreak.vastUrls.length > 0;\n\n const durationMs =\n marker.durationSeconds != null\n ? marker.durationSeconds * 1000\n : (this.pendingAdBreak?.marker.durationSeconds != null \n ? this.pendingAdBreak.marker.durationSeconds * 1000 \n : undefined);\n\n const isManifestMarker = this.isManifestBasedMarker(marker);\n const forceImmediate = this.config.immediateManifestAds ?? true;\n\n if (this.config.debugAdTiming) {\n console.log(\"[StormcloudVideoPlayer] Ad start decision:\", {\n isManifestMarker,\n forceImmediate,\n hasPts: typeof marker.ptsSeconds === \"number\",\n hasPrefetchedAds,\n });\n }\n\n if (isManifestMarker && forceImmediate) {\n if (this.config.debugAdTiming) {\n console.log(\n `[StormcloudVideoPlayer] Starting ad immediately (manifest-based)${hasPrefetchedAds ? \" with prefetched ads\" : \"\"}`\n );\n }\n this.clearAdStartTimer();\n this.startScte35AdBreak(marker, cueKey, durationMs);\n } else if (typeof marker.ptsSeconds === \"number\") {\n const tol = this.config.driftToleranceMs ?? 1000;\n const nowMs = this.video.currentTime * 1000;\n const estCurrentPtsMs = nowMs - this.ptsDriftEmaMs;\n const deltaMs = Math.floor(marker.ptsSeconds * 1000 - estCurrentPtsMs);\n\n if (this.config.debugAdTiming) {\n console.log(\"[StormcloudVideoPlayer] PTS-based timing calculation:\", {\n nowMs,\n estCurrentPtsMs,\n markerPtsMs: marker.ptsSeconds * 1000,\n deltaMs,\n tolerance: tol,\n });\n }\n\n if (deltaMs > tol) {\n if (this.config.debugAdTiming) {\n console.log(\n `[StormcloudVideoPlayer] Scheduling ad start in ${deltaMs}ms`\n );\n }\n this.expectedAdBreakDurationMs = durationMs;\n this.scheduledScte35BreakKey = cueKey;\n this.scheduleAdStartIn(deltaMs, marker, cueKey);\n } else {\n if (this.config.debugAdTiming) {\n console.log(\n \"[StormcloudVideoPlayer] Starting ad immediately (within tolerance)\"\n );\n }\n this.clearAdStartTimer();\n this.startScte35AdBreak(marker, cueKey, durationMs);\n }\n } else {\n if (this.config.debugAdTiming) {\n console.log(\n \"[StormcloudVideoPlayer] Starting ad immediately (fallback)\"\n );\n }\n this.clearAdStartTimer();\n this.startScte35AdBreak(marker, cueKey, durationMs);\n }\n return;\n }\n if (marker.type === \"progress\" && this.inAdBreak) {\n if (marker.durationSeconds != null) {\n this.expectedAdBreakDurationMs = marker.durationSeconds * 1000;\n }\n if (\n this.expectedAdBreakDurationMs != null &&\n this.currentAdBreakStartWallClockMs != null\n ) {\n const elapsedMs = Date.now() - this.currentAdBreakStartWallClockMs;\n const remainingMs = Math.max(\n 0,\n this.expectedAdBreakDurationMs - elapsedMs\n );\n this.scheduleAdStopCountdown(remainingMs);\n }\n \n if (!this.adPlayer.isAdPlaying() && this.activeAdRequestToken === null && this.adRequestQueue.length > 0) {\n this.tryNextAvailableAdWithRateLimit();\n }\n return;\n }\n if (marker.type === \"end\") {\n if (!this.video.muted) {\n this.video.muted = true;\n this.video.volume = 0;\n if (this.config.debugAdTiming) {\n console.log(\"[StormcloudVideoPlayer] Muted video on SCTE end marker\");\n }\n }\n\n const remaining = this.getRemainingAdMs();\n const adPlaying = this.adPlayer.isAdPlaying();\n const hasQueuedAds = this.adRequestQueue.length > 0;\n \n if (this.config.debugAdTiming) {\n console.log(\"[StormcloudVideoPlayer] SCTE-35 end marker received:\", {\n remaining,\n adPlaying,\n hasQueuedAds,\n activeAdRequest: this.activeAdRequestToken !== null,\n });\n }\n \n if (adPlaying || (remaining > 1000 && hasQueuedAds)) {\n if (this.config.debugAdTiming) {\n console.log(\"[StormcloudVideoPlayer] Ignoring premature SCTE-35 end marker - ads still active\");\n }\n return;\n }\n \n this.inAdBreak = false;\n this.expectedAdBreakDurationMs = undefined;\n this.currentAdBreakStartWallClockMs = undefined;\n this.clearAdStartTimer();\n this.clearAdStopTimer();\n \n if (adPlaying) {\n this.adPlayer.stop().catch(() => {});\n }\n \n this.handleAdPodComplete();\n return;\n }\n }\n\n private startScte35AdBreak(\n marker: Scte35Marker,\n cueKey: string | undefined,\n durationMs: number | undefined\n ): void {\n if (!this.video.muted) {\n this.video.muted = true;\n this.video.volume = 0;\n if (this.config.debugAdTiming) {\n console.log(\"[StormcloudVideoPlayer] Muted video on SCTE start marker\");\n }\n }\n\n this.inAdBreak = true;\n this.activeScte35BreakKey = cueKey ?? this.pendingScte35CueKey;\n this.scheduledScte35BreakKey = undefined;\n this.expectedAdBreakDurationMs = durationMs;\n this.currentAdBreakStartWallClockMs = Date.now();\n\n this.handleAdStart(marker);\n\n if (this.expectedAdBreakDurationMs != null) {\n this.scheduleAdStopCountdown(this.expectedAdBreakDurationMs);\n }\n }\n\n private parseCueOutDuration(value: string): number | undefined {\n const num = parseFloat(value.trim());\n if (!Number.isNaN(num)) return num;\n const match =\n value.match(/(?:^|[,\\s])DURATION\\s*=\\s*([0-9.]+)/i) ||\n value.match(/Duration\\s*=\\s*([0-9.]+)/i);\n if (match && match[1] != null) {\n const dStr = match[1];\n const d = parseFloat(dStr);\n return Number.isNaN(d) ? undefined : d;\n }\n return undefined;\n }\n\n private parseCueOutCont(\n value: string\n ): { elapsed?: number; duration?: number } | undefined {\n const res: { elapsed?: number; duration?: number } = {};\n \n const elapsedMatch = value.match(/Elapsed\\s*=\\s*([0-9.]+)/i);\n const durationMatch = value.match(/Duration\\s*=\\s*([0-9.]+)/i);\n if (elapsedMatch && elapsedMatch[1] != null) {\n const e = parseFloat(elapsedMatch[1]);\n if (!Number.isNaN(e)) res.elapsed = e;\n }\n if (durationMatch && durationMatch[1] != null) {\n const d = parseFloat(durationMatch[1]);\n if (!Number.isNaN(d)) res.duration = d;\n }\n \n if (!(\"elapsed\" in res) || !(\"duration\" in res)) {\n const slashMatch = value.match(/([0-9.]+)\\s*\\/\\s*([0-9.]+)/);\n if (slashMatch && slashMatch[1] && slashMatch[2]) {\n const elapsed = parseFloat(slashMatch[1]);\n const duration = parseFloat(slashMatch[2]);\n if (!Number.isNaN(elapsed) && !(\"elapsed\" in res)) res.elapsed = elapsed;\n if (!Number.isNaN(duration) && !(\"duration\" in res)) res.duration = duration;\n }\n }\n \n if (\"elapsed\" in res || \"duration\" in res) return res;\n return undefined;\n }\n\n private parseAttributeList(value: string): Record<string, string> {\n const attrs: Record<string, string> = {};\n const regex = /([A-Z0-9-]+)=((\"[^\"]*\")|([^\",]*))(?:,|$)/gi;\n let match: RegExpExecArray | null;\n while ((match = regex.exec(value)) !== null) {\n const key: string = (match[1] ?? \"\") as string;\n let rawVal: string = (match[3] ?? match[4] ?? \"\") as string;\n if (rawVal.startsWith('\"') && rawVal.endsWith('\"')) {\n rawVal = rawVal.slice(1, -1);\n }\n if (key) {\n attrs[key] = rawVal;\n }\n }\n return attrs;\n }\n\n private toNumber(val: unknown): number | undefined {\n if (val == null) return undefined;\n const n = typeof val === \"string\" ? parseFloat(val) : Number(val);\n return Number.isNaN(n) ? undefined : n;\n }\n\n private isManifestBasedMarker(marker: Scte35Marker): boolean {\n const raw = marker.raw as any;\n if (!raw) return false;\n\n if (raw.tag) {\n const tag = String(raw.tag);\n return (\n tag.includes(\"EXT-X-CUE-OUT\") ||\n tag.includes(\"EXT-X-CUE-IN\") ||\n tag.includes(\"EXT-X-DATERANGE\")\n );\n }\n\n if (raw.id3) return false;\n\n if (raw.splice_command_type) return false;\n\n return false;\n }\n\n private normalizeFragmentPayload(payload: unknown): Uint8Array | undefined {\n if (payload instanceof Uint8Array) {\n return payload;\n }\n if (payload instanceof ArrayBuffer) {\n return new Uint8Array(payload);\n }\n if (ArrayBuffer.isView(payload)) {\n const view = payload as ArrayBufferView;\n return new Uint8Array(view.buffer, view.byteOffset, view.byteLength);\n }\n return undefined;\n }\n\n private processFragmentScte35Payload(\n payloadData: unknown,\n fragmentSn?: number,\n fragmentStartSeconds?: number\n ): void {\n const payload = this.normalizeFragmentPayload(payloadData);\n if (!payload) {\n return;\n }\n\n const markers = this.parseScte35FromTsPackets(payload);\n markers.forEach((marker) => {\n const context: Scte35CueContext = {\n source: \"ts\",\n readiness: \"early\",\n };\n if (fragmentSn !== undefined) {\n context.fragmentSn = fragmentSn;\n }\n if (fragmentStartSeconds !== undefined) {\n context.fragmentStartSeconds = fragmentStartSeconds;\n }\n this.onScte35Cue(marker, context);\n });\n }\n\n private parseScte35FromTsPackets(data: Uint8Array): Scte35Marker[] {\n const packetInfo = this.detectTsPacketFormat(data);\n if (!packetInfo) {\n return [];\n }\n\n const markers: Scte35Marker[] = [];\n const sectionAssemblers = new Map<\n number,\n { bytes: number[]; expectedLength: number }\n >();\n\n for (\n let packetStart = packetInfo.offset;\n packetStart + packetInfo.packetSize <= data.length;\n packetStart += packetInfo.packetSize\n ) {\n const tsStart = packetStart + packetInfo.tsPayloadOffset;\n if (data[tsStart] !== 0x47) {\n continue;\n }\n\n const secondByte = data[tsStart + 1];\n const thirdByte = data[tsStart + 2];\n const fourthByte = data[tsStart + 3];\n if (\n secondByte == null ||\n thirdByte == null ||\n fourthByte == null ||\n (secondByte & 0x80) !== 0\n ) {\n continue;\n }\n\n const payloadUnitStart = (secondByte & 0x40) !== 0;\n const pid = ((secondByte & 0x1f) << 8) | thirdByte;\n const adaptationFieldControl = (fourthByte >> 4) & 0x03;\n const hasPayload =\n adaptationFieldControl === 1 || adaptationFieldControl === 3;\n if (!hasPayload) {\n continue;\n }\n\n let payloadStart = tsStart + 4;\n if (adaptationFieldControl === 3) {\n const adaptationLength = data[payloadStart];\n if (adaptationLength == null) {\n continue;\n }\n payloadStart += 1 + adaptationLength;\n }\n\n const payloadEnd = Math.min(tsStart + 188, data.length);\n if (payloadStart >= payloadEnd || payloadStart >= data.length) {\n continue;\n }\n\n const payload = data.subarray(payloadStart, payloadEnd);\n if (pid === 0) {\n this.parsePatSection(payload, payloadUnitStart);\n } else if (this.pmtPids.has(pid)) {\n this.parsePmtSection(payload, payloadUnitStart);\n } else if (this.tsScte35Pids.has(pid)) {\n this.collectScte35SectionsFromPayload(\n pid,\n payload,\n payloadUnitStart,\n sectionAssemblers,\n markers\n );\n }\n }\n\n return markers;\n }\n\n private detectTsPacketFormat(\n data: Uint8Array\n ): { offset: number; packetSize: number; tsPayloadOffset: number } | undefined {\n const packetSizes = [188, 192, 204];\n for (const packetSize of packetSizes) {\n const tsPayloadOffset = packetSize === 192 ? 4 : 0;\n for (let offset = 0; offset < packetSize; offset++) {\n let matchedPackets = 0;\n for (\n let packetStart = offset;\n packetStart + tsPayloadOffset < data.length &&\n matchedPackets < 5;\n packetStart += packetSize\n ) {\n if (data[packetStart + tsPayloadOffset] !== 0x47) {\n break;\n }\n matchedPackets++;\n }\n if (matchedPackets >= 2) {\n return { offset, packetSize, tsPayloadOffset };\n }\n }\n }\n return undefined;\n }\n\n private parsePatSection(payload: Uint8Array, payloadUnitStart: boolean): void {\n const sectionStart = this.getPsiSectionStart(payload, payloadUnitStart);\n if (sectionStart == null || sectionStart + 8 >= payload.length) {\n return;\n }\n if (payload[sectionStart] !== 0x00) {\n return;\n }\n\n const sectionLength = this.getPsiSectionLength(payload, sectionStart);\n const sectionEnd = Math.min(\n payload.length,\n sectionStart + 3 + sectionLength\n );\n\n for (let offset = sectionStart + 8; offset + 4 <= sectionEnd - 4; offset += 4) {\n const programNumber =\n ((payload[offset] ?? 0) << 8) | (payload[offset + 1] ?? 0);\n const pid =\n (((payload[offset + 2] ?? 0) & 0x1f) << 8) |\n (payload[offset + 3] ?? 0);\n if (programNumber !== 0) {\n this.pmtPids.add(pid);\n }\n }\n }\n\n private parsePmtSection(payload: Uint8Array, payloadUnitStart: boolean): void {\n const sectionStart = this.getPsiSectionStart(payload, payloadUnitStart);\n if (sectionStart == null || sectionStart + 12 >= payload.length) {\n return;\n }\n if (payload[sectionStart] !== 0x02) {\n return;\n }\n\n const sectionLength = this.getPsiSectionLength(payload, sectionStart);\n const sectionEnd = Math.min(\n payload.length,\n sectionStart + 3 + sectionLength\n );\n const programInfoLength =\n (((payload[sectionStart + 10] ?? 0) & 0x0f) << 8) |\n (payload[sectionStart + 11] ?? 0);\n\n let offset = sectionStart + 12 + programInfoLength;\n while (offset + 5 <= sectionEnd - 4) {\n const streamType = payload[offset] ?? 0;\n const elementaryPid =\n (((payload[offset + 1] ?? 0) & 0x1f) << 8) |\n (payload[offset + 2] ?? 0);\n const esInfoLength =\n (((payload[offset + 3] ?? 0) & 0x0f) << 8) |\n (payload[offset + 4] ?? 0);\n const descriptorStart = offset + 5;\n const descriptorEnd = Math.min(descriptorStart + esInfoLength, sectionEnd - 4);\n\n if (\n streamType === 0x86 ||\n (streamType === 0x06 &&\n this.descriptorsIdentifyScte35(payload, descriptorStart, descriptorEnd))\n ) {\n this.tsScte35Pids.add(elementaryPid);\n }\n\n offset = descriptorStart + esInfoLength;\n }\n }\n\n private descriptorsIdentifyScte35(\n data: Uint8Array,\n start: number,\n end: number\n ): boolean {\n let offset = start;\n while (offset + 2 <= end) {\n const tag = data[offset] ?? 0;\n const length = data[offset + 1] ?? 0;\n const descriptorStart = offset + 2;\n const descriptorEnd = descriptorStart + length;\n if (descriptorEnd > end) {\n return false;\n }\n\n const registration =\n length >= 4\n ? String.fromCharCode(\n data[descriptorStart] ?? 0,\n data[descriptorStart + 1] ?? 0,\n data[descriptorStart + 2] ?? 0,\n data[descriptorStart + 3] ?? 0\n )\n : \"\";\n if (tag === 0x8a || registration === \"CUEI\" || registration === \"SCTE\") {\n return true;\n }\n\n offset = descriptorEnd;\n }\n return false;\n }\n\n private collectScte35SectionsFromPayload(\n pid: number,\n payload: Uint8Array,\n payloadUnitStart: boolean,\n assemblers: Map<number, { bytes: number[]; expectedLength: number }>,\n markers: Scte35Marker[]\n ): void {\n if (payload.length === 0) {\n return;\n }\n\n let offset = 0;\n if (payloadUnitStart) {\n const pointerField = payload[0] ?? 0;\n const previousAssembler = assemblers.get(pid);\n if (previousAssembler && pointerField > 0) {\n this.appendScte35Bytes(\n pid,\n payload.subarray(1, Math.min(1 + pointerField, payload.length)),\n assemblers,\n markers\n );\n }\n assemblers.delete(pid);\n offset = 1 + pointerField;\n } else {\n this.appendScte35Bytes(pid, payload, assemblers, markers);\n return;\n }\n\n while (offset + 3 <= payload.length) {\n const tableId = payload[offset];\n if (tableId == null || tableId === 0xff) {\n return;\n }\n\n const sectionLength = this.getPsiSectionLength(payload, offset);\n const totalLength = 3 + sectionLength;\n if (sectionLength <= 0 || totalLength <= 3) {\n return;\n }\n\n if (offset + totalLength <= payload.length) {\n this.addScte35SectionMarker(\n payload.subarray(offset, offset + totalLength),\n markers\n );\n offset += totalLength;\n } else {\n assemblers.set(pid, {\n bytes: Array.from(payload.subarray(offset)),\n expectedLength: totalLength,\n });\n return;\n }\n }\n }\n\n private appendScte35Bytes(\n pid: number,\n bytes: Uint8Array,\n assemblers: Map<number, { bytes: number[]; expectedLength: number }>,\n markers: Scte35Marker[]\n ): void {\n const assembler = assemblers.get(pid);\n if (!assembler) {\n return;\n }\n\n for (let i = 0; i < bytes.length && assembler.bytes.length < assembler.expectedLength; i++) {\n assembler.bytes.push(bytes[i] ?? 0);\n }\n\n if (assembler.bytes.length >= assembler.expectedLength) {\n assemblers.delete(pid);\n this.addScte35SectionMarker(new Uint8Array(assembler.bytes), markers);\n }\n }\n\n private addScte35SectionMarker(\n section: Uint8Array,\n markers: Scte35Marker[]\n ): void {\n if (section[0] !== 0xfc || this.hasProcessedTsScte35Section(section)) {\n return;\n }\n\n const marker = this.parseScte35Binary(section);\n if (!marker) {\n return;\n }\n\n marker.raw = {\n ...(typeof marker.raw === \"object\" && marker.raw ? marker.raw : {}),\n source: \"ts-packet\",\n };\n markers.push(marker);\n }\n\n private hasProcessedTsScte35Section(section: Uint8Array): boolean {\n let checksum = 0;\n for (let i = 0; i < section.length; i++) {\n checksum = (checksum * 31 + (section[i] ?? 0)) >>> 0;\n }\n\n const key = `${section.length}:${checksum}`;\n if (this.processedTsScte35Sections.has(key)) {\n return true;\n }\n\n this.processedTsScte35Sections.add(key);\n if (this.processedTsScte35Sections.size > 200) {\n const firstKey = this.processedTsScte35Sections.values().next().value;\n if (firstKey) {\n this.processedTsScte35Sections.delete(firstKey);\n }\n }\n return false;\n }\n\n private getPsiSectionStart(\n payload: Uint8Array,\n payloadUnitStart: boolean\n ): number | undefined {\n if (!payloadUnitStart) {\n return undefined;\n }\n const pointerField = payload[0];\n if (pointerField == null) {\n return undefined;\n }\n const sectionStart = 1 + pointerField;\n return sectionStart < payload.length ? sectionStart : undefined;\n }\n\n private getPsiSectionLength(data: Uint8Array, offset: number): number {\n return (((data[offset + 1] ?? 0) & 0x0f) << 8) | (data[offset + 2] ?? 0);\n }\n\n private parseScte35Binary(data: Uint8Array): Scte35Marker | undefined {\n class BitReader {\n private bytePos = 0;\n private bitPos = 0;\n constructor(private readonly buf: Uint8Array) {}\n readBits(numBits: number): number {\n let result = 0;\n while (numBits > 0) {\n if (this.bytePos >= this.buf.length) return result;\n const remainingInByte = 8 - this.bitPos;\n const toRead = Math.min(numBits, remainingInByte);\n const currentByte = this.buf[this.bytePos]!;\n const shift = remainingInByte - toRead;\n const mask = ((1 << toRead) - 1) & 0xff;\n const bits = (currentByte >> shift) & mask;\n result = (result << toRead) | bits;\n this.bitPos += toRead;\n if (this.bitPos >= 8) {\n this.bitPos = 0;\n this.bytePos += 1;\n }\n numBits -= toRead;\n }\n return result >>> 0;\n }\n skipBits(n: number): void {\n this.readBits(n);\n }\n get bytePosition(): number {\n return this.bitPos === 0 ? this.bytePos : this.bytePos + 1;\n }\n }\n\n const readSpliceTime = (\n r: BitReader,\n ptsAdjustmentTicks: number\n ): number | undefined => {\n const timeSpecifiedFlag = r.readBits(1) === 1;\n if (!timeSpecifiedFlag) {\n r.readBits(7);\n return undefined;\n }\n r.readBits(6);\n const high = r.readBits(1);\n const low = r.readBits(32);\n const ptsTicks =\n (high * 0x100000000 + low + ptsAdjustmentTicks) % 0x200000000;\n return ptsTicks / 90000;\n };\n\n const r = new BitReader(data);\n const tableId = r.readBits(8);\n if (tableId !== 0xfc) return undefined;\n r.readBits(1);\n r.readBits(1);\n r.readBits(2);\n const sectionLength = r.readBits(12);\n if (sectionLength <= 0 || data.length < 3 + sectionLength) {\n return undefined;\n }\n r.readBits(8);\n r.readBits(1);\n r.readBits(6);\n const ptsAdjHigh = r.readBits(1);\n const ptsAdjLow = r.readBits(32);\n const ptsAdjustmentTicks = ptsAdjHigh * 0x100000000 + ptsAdjLow;\n r.readBits(8);\n r.readBits(12);\n const spliceCommandLength = r.readBits(12);\n const spliceCommandType = r.readBits(8);\n\n let markerType: Scte35Marker[\"type\"] | undefined;\n let durationSeconds: number | undefined = undefined;\n let ptsSeconds: number | undefined = undefined;\n let spliceEventId: number | undefined = undefined;\n const commandBodyStart = r.bytePosition;\n\n if (spliceCommandType === 5) {\n spliceEventId = r.readBits(32);\n const cancel = r.readBits(1) === 1;\n r.readBits(7);\n if (cancel) return undefined;\n const outOfNetwork = r.readBits(1) === 1;\n const programSpliceFlag = r.readBits(1) === 1;\n const durationFlag = r.readBits(1) === 1;\n const spliceImmediateFlag = r.readBits(1) === 1;\n r.readBits(4);\n markerType = outOfNetwork ? \"start\" : \"end\";\n\n if (programSpliceFlag && !spliceImmediateFlag) {\n ptsSeconds = readSpliceTime(r, ptsAdjustmentTicks);\n } else if (!programSpliceFlag) {\n const componentCount = r.readBits(8);\n for (let i = 0; i < componentCount; i++) {\n r.readBits(8);\n if (!spliceImmediateFlag) {\n const componentPtsSeconds = readSpliceTime(r, ptsAdjustmentTicks);\n if (ptsSeconds === undefined) {\n ptsSeconds = componentPtsSeconds;\n }\n }\n }\n }\n\n if (durationFlag) {\n r.readBits(6);\n r.readBits(1);\n const high = r.readBits(1);\n const low = r.readBits(32);\n const durationTicks = high * 0x100000000 + low;\n durationSeconds = durationTicks / 90000;\n }\n r.readBits(16);\n r.readBits(8);\n r.readBits(8);\n } else if (spliceCommandType === 6) {\n ptsSeconds = readSpliceTime(r, ptsAdjustmentTicks);\n } else {\n return undefined;\n }\n\n const expectedDescriptorOffset =\n spliceCommandLength === 0x0fff\n ? r.bytePosition\n : commandBodyStart + spliceCommandLength;\n const descriptorMarker = this.parseScte35SegmentationDescriptors(\n data,\n expectedDescriptorOffset\n );\n\n if (descriptorMarker) {\n markerType = descriptorMarker.type;\n if (durationSeconds === undefined) {\n durationSeconds = descriptorMarker.durationSeconds;\n }\n }\n\n if (!markerType) {\n return undefined;\n }\n\n const marker: Scte35Marker = {\n type: markerType,\n ...(ptsSeconds !== undefined ? { ptsSeconds } : {}),\n ...(durationSeconds !== undefined ? { durationSeconds } : {}),\n raw: {\n splice_command_type: spliceCommandType,\n ...(spliceEventId !== undefined ? { splice_event_id: spliceEventId } : {}),\n ...(descriptorMarker?.segmentationEventId !== undefined\n ? { segmentation_event_id: descriptorMarker.segmentationEventId }\n : {}),\n },\n } as Scte35Marker;\n return marker;\n }\n\n private parseScte35SegmentationDescriptors(\n data: Uint8Array,\n offset: number\n ):\n | {\n type: Scte35Marker[\"type\"];\n durationSeconds?: number;\n segmentationEventId?: number;\n }\n | undefined {\n if (offset + 2 > data.length) {\n return undefined;\n }\n\n const descriptorLoopLength =\n ((data[offset] ?? 0) << 8) | (data[offset + 1] ?? 0);\n let descriptorOffset = offset + 2;\n const descriptorEnd = Math.min(\n data.length,\n descriptorOffset + descriptorLoopLength\n );\n\n while (descriptorOffset + 2 <= descriptorEnd) {\n const descriptorTag = data[descriptorOffset] ?? 0;\n const descriptorLength = data[descriptorOffset + 1] ?? 0;\n const descriptorDataStart = descriptorOffset + 2;\n const descriptorDataEnd = descriptorDataStart + descriptorLength;\n if (descriptorDataEnd > descriptorEnd) {\n return undefined;\n }\n\n if (descriptorTag === 0x02) {\n const descriptorMarker = this.parseScte35SegmentationDescriptor(\n data.subarray(descriptorDataStart, descriptorDataEnd)\n );\n if (descriptorMarker) {\n return descriptorMarker;\n }\n }\n\n descriptorOffset = descriptorDataEnd;\n }\n\n return undefined;\n }\n\n private parseScte35SegmentationDescriptor(\n descriptor: Uint8Array\n ):\n | {\n type: Scte35Marker[\"type\"];\n durationSeconds?: number;\n segmentationEventId?: number;\n }\n | undefined {\n if (descriptor.length < 11) {\n return undefined;\n }\n\n const identifier = String.fromCharCode(\n descriptor[0] ?? 0,\n descriptor[1] ?? 0,\n descriptor[2] ?? 0,\n descriptor[3] ?? 0\n );\n if (identifier !== \"CUEI\") {\n return undefined;\n }\n\n const segmentationEventId =\n ((descriptor[4] ?? 0) * 0x1000000) +\n ((descriptor[5] ?? 0) << 16) +\n ((descriptor[6] ?? 0) << 8) +\n (descriptor[7] ?? 0);\n const cancelIndicator = ((descriptor[8] ?? 0) & 0x80) !== 0;\n if (cancelIndicator) {\n return undefined;\n }\n\n const flags = descriptor[9] ?? 0;\n const programSegmentationFlag = (flags & 0x80) !== 0;\n const segmentationDurationFlag = (flags & 0x40) !== 0;\n let offset = 10;\n\n if (!programSegmentationFlag) {\n const componentCount = descriptor[offset] ?? 0;\n offset += 1 + componentCount * 6;\n if (offset > descriptor.length) {\n return undefined;\n }\n }\n\n let durationSeconds: number | undefined = undefined;\n if (segmentationDurationFlag) {\n if (offset + 5 > descriptor.length) {\n return undefined;\n }\n const durationTicks =\n ((descriptor[offset] ?? 0) * 0x100000000) +\n ((descriptor[offset + 1] ?? 0) * 0x1000000) +\n ((descriptor[offset + 2] ?? 0) << 16) +\n ((descriptor[offset + 3] ?? 0) << 8) +\n (descriptor[offset + 4] ?? 0);\n durationSeconds = durationTicks / 90000;\n offset += 5;\n }\n\n if (offset + 2 > descriptor.length) {\n return undefined;\n }\n offset += 1;\n const segmentationUpidLength = descriptor[offset] ?? 0;\n offset += 1 + segmentationUpidLength;\n if (offset >= descriptor.length) {\n return undefined;\n }\n\n const segmentationTypeId = descriptor[offset] ?? 0;\n const markerType = this.markerTypeFromSegmentationTypeId(segmentationTypeId);\n if (!markerType) {\n return undefined;\n }\n\n return {\n type: markerType,\n ...(durationSeconds !== undefined ? { durationSeconds } : {}),\n segmentationEventId,\n };\n }\n\n private markerTypeFromSegmentationTypeId(\n segmentationTypeId: number\n ): Scte35Marker[\"type\"] | undefined {\n switch (segmentationTypeId) {\n case 0x10:\n case 0x22:\n case 0x30:\n case 0x32:\n case 0x34:\n case 0x36:\n return \"start\";\n case 0x11:\n case 0x23:\n case 0x31:\n case 0x33:\n case 0x35:\n case 0x37:\n return \"end\";\n default:\n return undefined;\n }\n }\n\n private initializeTracking(): void {\n sendInitialTracking(this.config.licenseKey)\n .then(() => {\n this.heartbeatInterval = window.setInterval(() => {\n this.sendHeartbeatIfNeeded();\n }, 5000);\n })\n .catch((error) => {\n if (this.config.debugAdTiming) {\n console.warn(\n \"[StormcloudVideoPlayer] Failed to send initial tracking:\",\n error\n );\n }\n this.heartbeatInterval = window.setInterval(() => {\n this.sendHeartbeatIfNeeded();\n }, 5000);\n });\n }\n\n private sendHeartbeatIfNeeded(): void {\n const now = Date.now();\n if (!this.lastHeartbeatTime || now - this.lastHeartbeatTime > 30000) {\n this.lastHeartbeatTime = now;\n sendHeartbeat(this.config.licenseKey).catch((error) => {\n if (this.config.debugAdTiming) {\n console.warn(\n \"[StormcloudVideoPlayer] Failed to send heartbeat:\",\n error\n );\n }\n });\n }\n }\n\n private async fetchAdConfiguration(): Promise<void> {\n if (this.config.vmapUrl) {\n await this.fetchAndParseVmap(this.config.vmapUrl);\n }\n\n const vastMode = this.config.vastMode || \"default\";\n\n if (this.config.debugAdTiming) {\n console.log(\"[StormcloudVideoPlayer] VAST mode:\", vastMode);\n }\n\n if (vastMode === \"adstorm\") {\n if (!this.config.licenseKey) {\n if (this.config.debugAdTiming) {\n console.warn(\n \"[StormcloudVideoPlayer] AdStorm mode requires a license key\"\n );\n }\n return;\n }\n\n const vastEndpoint = `https://adstorm.co/api-adstorm-dev/adstorm/vast/${this.config.licenseKey}`;\n this.apiVastTagUrl = vastEndpoint;\n\n if (this.config.debugAdTiming) {\n console.log(\n \"[StormcloudVideoPlayer] Using AdStorm VAST endpoint (adstorm mode):\",\n vastEndpoint\n );\n }\n return;\n }\n\n if (this.config.vastTagUrl) {\n this.apiVastTagUrl = this.config.vastTagUrl;\n if (this.config.debugAdTiming) {\n console.log(\n \"[StormcloudVideoPlayer] Using custom VAST tag URL:\",\n this.apiVastTagUrl\n );\n }\n return;\n }\n\n const apiUrl = \"https://adstorm.co/api-adstorm-dev/adstorm/ads/web\";\n\n if (this.config.debugAdTiming) {\n console.log(\n \"[StormcloudVideoPlayer] Fetching ad configuration from:\",\n apiUrl\n );\n }\n\n const headers: Record<string, string> = {};\n if (this.config.licenseKey) {\n headers[\"Authorization\"] = `Bearer ${this.config.licenseKey}`;\n }\n\n const response = await fetch(apiUrl, { headers });\n if (!response.ok) {\n if (this.config.debugAdTiming) {\n console.warn(\n `[StormcloudVideoPlayer] Failed to fetch ad configuration: ${response.status}`\n );\n }\n return;\n }\n\n const data: StormcloudApiResponse = await response.json();\n\n const imaPayload = data.response?.ima?.[\"publisherdesk.ima\"]?.payload;\n if (imaPayload) {\n this.apiVastTagUrl = decodeURIComponent(imaPayload);\n if (this.config.debugAdTiming) {\n console.log(\n \"[StormcloudVideoPlayer] Extracted VAST tag URL from /ads/web:\",\n this.apiVastTagUrl\n );\n }\n } else {\n if (this.config.debugAdTiming) {\n console.warn(\n \"[StormcloudVideoPlayer] No VAST tag URL found in /ads/web response\"\n );\n }\n }\n\n const numberAds = data.response?.options?.vast?.cue_tones?.number_ads;\n if (numberAds != null && numberAds > 0) {\n this.apiNumberAds = numberAds;\n if (this.config.debugAdTiming) {\n console.log(\n \"[StormcloudVideoPlayer] Number of ads per break from API:\",\n this.apiNumberAds\n );\n }\n }\n }\n\n private async fetchAndParseVmap(vmapUrl: string): Promise<void> {\n if (!vmapUrl.trim()) {\n return;\n }\n\n try {\n const response = await fetch(vmapUrl);\n if (!response.ok) {\n throw new Error(`Failed to fetch VMAP (${response.status})`);\n }\n\n const vmapXml = await response.text();\n this.vmapBreaks = this.parseVmapToBreaks(vmapXml);\n this.consumedVmapBreakIds.clear();\n\n if (this.config.debugAdTiming) {\n console.log(\n `[StormcloudVideoPlayer] Loaded ${this.vmapBreaks.length} VMAP ad break(s) from:`,\n vmapUrl\n );\n }\n } catch (error) {\n this.vmapBreaks = [];\n this.consumedVmapBreakIds.clear();\n if (this.config.debugAdTiming) {\n console.warn(\"[StormcloudVideoPlayer] Failed to load VMAP:\", error);\n }\n }\n }\n\n private parseVmapToBreaks(vmapXml: string): AdBreak[] {\n if (typeof DOMParser === \"undefined\") {\n return [];\n }\n\n const doc = new DOMParser().parseFromString(vmapXml, \"application/xml\");\n if (doc.querySelector(\"parsererror\")) {\n if (this.config.debugAdTiming) {\n console.warn(\"[StormcloudVideoPlayer] Invalid VMAP XML received\");\n }\n return [];\n }\n\n const adBreakNodes = Array.from(\n doc.querySelectorAll(\"AdBreak, vmap\\\\:AdBreak\")\n );\n const parsed: AdBreak[] = [];\n\n adBreakNodes.forEach((node, index) => {\n const timeOffsetRaw = (node.getAttribute(\"timeOffset\") || \"\").trim();\n const startTimeMs = this.parseVmapTimeOffsetToMs(timeOffsetRaw);\n if (startTimeMs == null) {\n return;\n }\n\n const adTagNode = node.querySelector(\"AdTagURI, vmap\\\\:AdTagURI\");\n const adTagUrl = (adTagNode?.textContent || \"\").trim();\n if (!adTagUrl) {\n return;\n }\n\n const breakId =\n node.getAttribute(\"breakId\") ||\n `vmap-break-${index}-${timeOffsetRaw || \"unknown\"}`;\n parsed.push({\n id: breakId,\n startTimeMs,\n vastTagUrl: adTagUrl,\n });\n });\n\n parsed.sort((a, b) => {\n const aStart = a.startTimeMs < 0 ? Number.MAX_SAFE_INTEGER : a.startTimeMs;\n const bStart = b.startTimeMs < 0 ? Number.MAX_SAFE_INTEGER : b.startTimeMs;\n return aStart - bStart;\n });\n\n return parsed;\n }\n\n private parseVmapTimeOffsetToMs(timeOffset: string): number | undefined {\n if (!timeOffset) {\n return undefined;\n }\n\n const normalized = timeOffset.trim().toLowerCase();\n if (normalized === \"start\") {\n return 0;\n }\n\n if (normalized === \"end\") {\n // Post-roll: resolved using current media duration at runtime.\n return -1;\n }\n\n const hms = timeOffset.match(\n /^(\\d{1,2}):(\\d{2}):(\\d{2})(?:\\.(\\d{1,3}))?$/\n );\n if (hms) {\n const [, hh, mm, ss, ms = \"0\"] = hms;\n const hours = Number(hh);\n const minutes = Number(mm);\n const seconds = Number(ss);\n const millis = Number(ms.padEnd(3, \"0\").slice(0, 3));\n return ((hours * 3600 + minutes * 60 + seconds) * 1000) + millis;\n }\n\n const percent = timeOffset.match(/^(\\d+(?:\\.\\d+)?)%$/);\n if (percent) {\n const ratio = Number(percent[1]) / 100;\n const durationSec = this.video.duration;\n if (Number.isFinite(durationSec) && durationSec > 0) {\n return Math.floor(durationSec * 1000 * ratio);\n }\n return undefined;\n }\n\n return undefined;\n }\n\n private getAdBreakKey(adBreak: AdBreak): string {\n if (adBreak.id) {\n return adBreak.id;\n }\n return `${adBreak.startTimeMs}-${adBreak.vastTagUrl || \"\"}`;\n }\n\n private resolveBreakStartMs(adBreak: AdBreak): number | undefined {\n if (adBreak.startTimeMs >= 0) {\n return adBreak.startTimeMs;\n }\n\n // startTimeMs=-1 represents VMAP \"end\" and becomes post-roll.\n if (adBreak.startTimeMs === -1) {\n const durationSec = this.video.duration;\n if (Number.isFinite(durationSec) && durationSec > 0) {\n return Math.floor(durationSec * 1000);\n }\n }\n\n return undefined;\n }\n\n getCurrentAdIndex(): number {\n return this.currentAdIndex;\n }\n\n getTotalAdsInBreak(): number {\n return this.totalAdsInBreak;\n }\n\n getAdRemainingMs(): number {\n return this.getRemainingAdMs();\n }\n\n private generateVastUrlsWithCorrelators(\n baseUrl: string,\n count: number\n ): string[] {\n const urls: string[] = [];\n const baseTimestamp = Date.now();\n \n for (let i = 0; i < count; i++) {\n const timestamp = baseTimestamp + i;\n const random = Math.floor(Math.random() * 1000000000000);\n const uniqueCorrelator = `${timestamp}_${random}_${i}`;\n \n let urlWithCorrelator: string;\n \n const correlatorRegex = /([?&])correlator=([^&]*)/;\n if (correlatorRegex.test(baseUrl)) {\n urlWithCorrelator = baseUrl.replace(correlatorRegex, `$1correlator=${uniqueCorrelator}`);\n } else if (baseUrl.includes(\"?\")) {\n urlWithCorrelator = `${baseUrl}&correlator=${uniqueCorrelator}`;\n } else {\n urlWithCorrelator = `${baseUrl}?correlator=${uniqueCorrelator}`;\n }\n\n // Append PAL nonce as `givn` parameter for AdX demand without IMA SDK.\n urls.push(this.palNonce.injectNonce(urlWithCorrelator));\n }\n \n return urls;\n }\n\n isAdPlaying(): boolean {\n return this.inAdBreak && this.adPlayer.isAdPlaying();\n }\n\n isShowingAds(): boolean {\n return this.showAds;\n }\n\n getStreamType(): \"hls\" | \"other\" {\n const url = this.config.src.toLowerCase();\n if (\n url.includes(\".m3u8\") ||\n url.includes(\"/hls/\") ||\n url.includes(\"application/vnd.apple.mpegurl\")\n ) {\n return \"hls\";\n }\n return \"other\";\n }\n\n shouldShowNativeControls(): boolean {\n const streamType = this.getStreamType();\n if (streamType === \"other\") {\n return !(this.config.showCustomControls ?? false);\n }\n return !!(\n this.config.allowNativeHls && !(this.config.showCustomControls ?? false)\n );\n }\n\n private shouldContinueLiveStreamDuringAds(): boolean {\n if (this.config.allowNativeHls) {\n return false;\n }\n\n if (!this.isLiveStream) {\n return false;\n }\n\n return true;\n }\n\n private startAdPrefetch(\n marker: Scte35Marker,\n fragmentSn?: number,\n cueKey?: string\n ): void {\n if (this.pendingAdBreak || this.inAdBreak) {\n return;\n }\n\n const scheduled = this.findCurrentOrNextBreak(this.video.currentTime * 1000);\n const tags = this.selectVastTagsForBreak(scheduled);\n\n let baseVastUrl: string;\n if (tags && tags.length > 0 && tags[0]) {\n baseVastUrl = tags[0];\n } else if (this.apiVastTagUrl) {\n baseVastUrl = this.apiVastTagUrl;\n } else {\n if (this.config.debugAdTiming) {\n console.warn(\"[StormcloudVideoPlayer] No VAST URL available for prefetch\");\n }\n return;\n }\n\n const urlsToPregenerate = 5;\n const generatedUrls = this.generateVastUrlsWithCorrelators(baseVastUrl, urlsToPregenerate);\n\n this.pendingAdBreak = {\n marker,\n ...(fragmentSn !== undefined ? { detectedAtFragmentSn: fragmentSn } : {}),\n vastUrls: generatedUrls,\n isFetching: false,\n fetchStartTime: Date.now(),\n };\n this.pendingScte35CueKey = cueKey;\n\n this.adDetectSentForCurrentBreak = true;\n const detectPayload: {\n durationSeconds?: number;\n ptsSeconds?: number;\n detectedAtFragmentSn?: number;\n } = {};\n if (marker.durationSeconds != null) detectPayload.durationSeconds = marker.durationSeconds;\n if (marker.ptsSeconds != null) detectPayload.ptsSeconds = marker.ptsSeconds;\n if (fragmentSn !== undefined) detectPayload.detectedAtFragmentSn = fragmentSn;\n sendAdDetectTracking(this.config.licenseKey, { source: \"scte35\", timestamp: new Date().toISOString(), ...detectPayload }).catch(() => {});\n\n if (this.config.debugAdTiming) {\n console.log(\"[PREFETCH] 🔄 Starting ad prefetch for upcoming ad break\");\n console.log(`[PREFETCH] 📋 Pre-generated ${generatedUrls.length} VAST URLs`);\n }\n\n this.startPreloadPool(baseVastUrl, generatedUrls.slice(0, this.maxPreloadPoolSize));\n }\n\n private clearPendingAdBreak(): void {\n if (this.prefetchTimerId != null) {\n clearTimeout(this.prefetchTimerId);\n this.prefetchTimerId = undefined;\n }\n this.pendingAdBreak = null;\n this.pendingScte35CueKey = undefined;\n }\n\n private startPreloadPool(baseVastUrl: string, initialUrls: string[]): void {\n if (this.preloadPoolActive) {\n if (this.config.debugAdTiming) {\n console.log(\"[PRELOAD-POOL] Already active, skipping duplicate start\");\n }\n return;\n }\n\n this.preloadPoolActive = true;\n \n if (this.config.debugAdTiming) {\n console.log(`[PRELOAD-POOL] 🏊 Starting preload pool EARLY (target size: ${this.maxPreloadPoolSize})`);\n console.log(`[PRELOAD-POOL] Ad break hasn't started yet, but preloading ads in advance`);\n }\n\n for (const url of initialUrls) {\n if (this.preloadPool.length < this.maxPreloadPoolSize) {\n this.preloadAdIntoPool(url);\n }\n }\n\n this.preloadPoolLoop(baseVastUrl);\n }\n\n private async preloadAdIntoPool(vastUrl: string): Promise<void> {\n if (this.isGamInCooldown()) {\n if (this.config.debugAdTiming) {\n console.log(\"[CIRCUIT-BREAKER] GAM in cooldown, skipping preload\");\n }\n return;\n }\n\n if (\n this.preloadPool.some(entry => entry.vastUrl === vastUrl) ||\n this.failedVastUrls.has(vastUrl) ||\n this.isUrlInCooldown(vastUrl)\n ) {\n return;\n }\n\n if (this.preloadPool.length >= this.maxPreloadPoolSize) {\n return;\n }\n\n if (this.config.debugAdTiming) {\n console.log(`[PRELOAD-POOL] 📥 Preloading ad into pool: ${vastUrl}`);\n }\n\n const loadPromise = (async () => {\n let hasAdError = false;\n let adErrorPayload: any = null;\n let errorListenerCleanup: (() => void) | null = null;\n \n try {\n const continueLiveStreamDuringAds = this.shouldContinueLiveStreamDuringAds();\n const preloadAd = this.createAdPlayer(continueLiveStreamDuringAds);\n preloadAd.initialize();\n \n const errorListener = (payload?: any) => {\n hasAdError = true;\n adErrorPayload = payload;\n };\n preloadAd.on(\"ad_error\", errorListener);\n errorListenerCleanup = () => preloadAd.off(\"ad_error\", errorListener);\n\n await this.enforceGlobalRateLimit();\n await preloadAd.requestAds(vastUrl);\n \n preloadAd.pause();\n \n await new Promise(resolve => setTimeout(resolve, 1500));\n \n preloadAd.pause();\n \n if (hasAdError) {\n const isNoFill = adErrorPayload?.isNoFill || \n adErrorPayload?.code === 303 || \n adErrorPayload?.vastErrorCode === 303;\n \n if (errorListenerCleanup) {\n errorListenerCleanup();\n }\n preloadAd.destroy();\n \n this.recordGamNoFill();\n\n if (isNoFill) {\n if (this.config.debugAdTiming) {\n console.log(`[PRELOAD-POOL] ⚠️ Ad preload returned no-fill: ${vastUrl}`);\n }\n this.temporaryFailureUrls.set(vastUrl, Date.now());\n } else {\n if (this.config.debugAdTiming) {\n console.log(`[PRELOAD-POOL] ⚠️ Ad preload failed with error: ${vastUrl}`, adErrorPayload);\n }\n if (adErrorPayload && !this.isTemporaryAdError(adErrorPayload as Error)) {\n this.failedVastUrls.add(vastUrl);\n } else {\n this.temporaryFailureUrls.set(vastUrl, Date.now());\n }\n }\n return;\n }\n \n const poolEntry = {\n vastUrl,\n adController: preloadAd,\n loadedAt: Date.now(),\n isReady: true,\n loadPromise: Promise.resolve(),\n };\n \n const lateErrorListener = (payload?: any) => {\n const index = this.preloadPool.findIndex(entry => entry.vastUrl === vastUrl);\n if (index >= 0) {\n this.preloadPool.splice(index, 1);\n if (this.config.debugAdTiming) {\n console.log(`[PRELOAD-POOL] ⚠️ Late error detected, removed from pool: ${vastUrl}`, payload);\n }\n try {\n preloadAd.destroy();\n } catch {}\n }\n };\n preloadAd.on(\"ad_error\", lateErrorListener);\n \n this.preloadPool.push(poolEntry);\n \n if (this.config.debugAdTiming) {\n console.log(`[PRELOAD-POOL] ✅ Ad preloaded (no errors detected within timeout) (pool size: ${this.preloadPool.length}/${this.maxPreloadPoolSize})`);\n }\n \n if (errorListenerCleanup) {\n errorListenerCleanup();\n }\n } catch (error) {\n if (errorListenerCleanup) {\n errorListenerCleanup();\n }\n \n this.recordGamNoFill();\n\n if (this.config.debugAdTiming) {\n console.warn(`[PRELOAD-POOL] ⚠️ Failed to preload ad: ${vastUrl}`, error);\n }\n \n if (error instanceof Error && !this.isTemporaryAdError(error)) {\n this.failedVastUrls.add(vastUrl);\n } else if (error instanceof Error && this.isTemporaryAdError(error)) {\n this.temporaryFailureUrls.set(vastUrl, Date.now());\n }\n }\n })();\n\n loadPromise.catch(() => {});\n }\n\n private async preloadPoolLoop(baseVastUrl: string): Promise<void> {\n if (this.preloadPoolLoopRunning) {\n return;\n }\n\n this.preloadPoolLoopRunning = true;\n\n if (this.config.debugAdTiming) {\n console.log(\"[PRELOAD-POOL] 🔄 Starting continuous preload loop\");\n }\n\n while (this.preloadPoolActive) {\n if (this.isGamInCooldown()) {\n if (this.config.debugAdTiming) {\n console.log(\"[CIRCUIT-BREAKER] GAM in cooldown, stopping preload pool loop\");\n }\n break;\n }\n\n if (!this.inAdBreak && this.preloadPool.length >= this.maxPreloadPoolSize) {\n await new Promise(resolve => setTimeout(resolve, 2000));\n continue;\n }\n\n if (!this.inAdBreak && this.pendingAdBreak === null) {\n if (this.config.debugAdTiming) {\n console.log(\"[PRELOAD-POOL] Ad break cancelled, stopping preload pool\");\n }\n break;\n }\n\n while (this.preloadPool.length < this.maxPreloadPoolSize) {\n if (!this.preloadPoolActive || this.isGamInCooldown()) {\n break;\n }\n\n if (this.inAdBreak) {\n const remaining = this.getRemainingAdMs();\n if (remaining <= 0) {\n break;\n }\n }\n\n const newUrls = this.generateVastUrlsWithCorrelators(baseVastUrl, 1);\n const newUrl = newUrls[0];\n \n if (newUrl && !this.failedVastUrls.has(newUrl) && !this.isUrlInCooldown(newUrl)) {\n await this.preloadAdIntoPool(newUrl);\n }\n\n await new Promise(resolve => setTimeout(resolve, 1000));\n }\n\n await new Promise(resolve => setTimeout(resolve, 2000));\n }\n\n this.preloadPoolLoopRunning = false;\n\n if (this.config.debugAdTiming) {\n console.log(\"[PRELOAD-POOL] 🛑 Preload loop ended\");\n }\n }\n\n private getPreloadedAd(): { vastUrl: string; adController: AdController } | null {\n if (this.preloadPool.length === 0) {\n return null;\n }\n\n const entry = this.preloadPool.shift();\n if (!entry || !entry.isReady) {\n return null;\n }\n\n if (this.config.debugAdTiming) {\n console.log(`[PRELOAD-POOL] 🎯 Using preloaded ad from pool (${this.preloadPool.length} remaining)`);\n }\n\n return {\n vastUrl: entry.vastUrl,\n adController: entry.adController,\n };\n }\n\n private stopPreloadPool(): void {\n this.preloadPoolActive = false;\n this.preloadPoolLoopRunning = false;\n\n for (const entry of this.preloadPool) {\n try {\n entry.adController.destroy();\n } catch (error) {\n if (this.config.debugAdTiming) {\n console.warn(\"[PRELOAD-POOL] Error destroying preloaded controller:\", error);\n }\n }\n }\n\n this.preloadPool = [];\n\n if (this.config.debugAdTiming) {\n console.log(\"[PRELOAD-POOL] 🛑 Preload pool stopped and cleaned up\");\n }\n }\n\n private async handleAdStart(_marker: Scte35Marker): Promise<void> {\n const scheduled = this.findCurrentOrNextBreak(\n this.video.currentTime * 1000\n );\n if (scheduled) {\n this.consumedVmapBreakIds.add(this.getAdBreakKey(scheduled));\n }\n const tags = this.selectVastTagsForBreak(scheduled);\n\n let baseVastUrl: string;\n\n if (tags && tags.length > 0 && tags[0]) {\n baseVastUrl = tags[0];\n } else if (this.apiVastTagUrl) {\n baseVastUrl = this.apiVastTagUrl;\n } else {\n this.clearPendingAdBreak();\n return;\n }\n\n const adBreakDurationMs = \n _marker.durationSeconds != null \n ? _marker.durationSeconds * 1000 \n : scheduled?.durationMs;\n\n if (this.config.debugAdTiming) {\n const mode = this.isLiveStream ? \"LIVE\" : \"VOD\";\n console.log(\n `[CONTINUOUS-FETCH] 📺 ${mode} MODE: Target duration=${adBreakDurationMs}ms`\n );\n }\n\n this.failedVastUrls.clear();\n this.temporaryFailureUrls.clear();\n this.consecutiveFailures = 0;\n this.continuousFetchingActive = true;\n this.isShowingPlaceholder = false;\n this.totalAdRequestsInBreak = 0;\n\n const currentMuted = this.video.muted;\n const currentVolume = this.video.volume;\n this.adPlayer.updateOriginalMutedState(currentMuted, currentVolume);\n\n if (!this.video.muted) {\n this.video.muted = true;\n this.video.volume = 0;\n if (this.config.debugAdTiming) {\n console.log(\"[StormcloudVideoPlayer] Muted video in handleAdStart\");\n }\n }\n\n this.inAdBreak = true;\n this.currentAdBreakStartWallClockMs = Date.now();\n this.currentAdIndex = 0;\n this.totalAdsInBreak = 1;\n this.adPodQueue = [];\n \n this.showAds = true;\n \n this.showPlaceholderLayer();\n this.adPlayer.showPlaceholder();\n\n if (\n this.expectedAdBreakDurationMs == null &&\n adBreakDurationMs != null\n ) {\n this.expectedAdBreakDurationMs = adBreakDurationMs;\n }\n\n let firstAdUrl: string | undefined;\n let usePreloadedAd = false;\n let preloadedController: AdController | undefined;\n \n const preloaded = this.getPreloadedAd();\n if (preloaded) {\n firstAdUrl = preloaded.vastUrl;\n preloadedController = preloaded.adController;\n usePreloadedAd = true;\n \n sendAdLoadedTracking(\n this.config.licenseKey,\n { source: \"hls\", vastUrl: firstAdUrl, timestamp: new Date().toISOString() }\n ).catch(() => {});\n if (this.config.debugAdTiming) {\n console.log(\"[CONTINUOUS-FETCH] 🚀 Using preloaded ad from pool (preloaded in advance, ready immediately!)\");\n console.log(`[CONTINUOUS-FETCH] Pool still has ${this.preloadPool.length} preloaded ads ready`);\n }\n } else if (this.pendingAdBreak && this.pendingAdBreak.vastUrls.length > 0) {\n this.adRequestQueue = [...this.pendingAdBreak.vastUrls];\n firstAdUrl = this.adRequestQueue.shift();\n \n if (this.config.debugAdTiming) {\n console.log(`[CONTINUOUS-FETCH] ⚠️ Pool empty, using prefetched URLs (${this.adRequestQueue.length + 1} available)`);\n }\n \n this.clearPendingAdBreak();\n } else {\n if (this.config.debugAdTiming) {\n console.log(\"[CONTINUOUS-FETCH] 🚀 Generating new ad URLs...\");\n }\n \n const firstAdUrlArray = this.generateVastUrlsWithCorrelators(baseVastUrl, 1);\n firstAdUrl = firstAdUrlArray[0];\n this.adRequestQueue = [];\n }\n \n if (!firstAdUrl) {\n if (this.config.debugAdTiming) {\n console.warn(\"[CONTINUOUS-FETCH] ⚠️ Failed to get first ad URL\");\n }\n this.handleAdPodComplete();\n return;\n }\n\n if (this.config.debugAdTiming) {\n console.log(\"[CONTINUOUS-FETCH] 📋 First VAST URL:\", firstAdUrl);\n }\n\n try {\n if (usePreloadedAd && preloadedController) {\n this.adPlayer.destroy();\n this.video.muted = true;\n this.video.volume = 0;\n this.adPlayer = preloadedController;\n \n this.attachImaEventListeners();\n \n if (this.config.debugAdTiming) {\n console.log(\"[CONTINUOUS-FETCH] ✅ Using preloaded ad, resuming and starting playback immediately (no request delay!)\");\n }\n \n this.adPlayer.resume();\n \n this.consecutiveFailures = 0;\n this.currentAdIndex++;\n this.startContinuousFetching(baseVastUrl);\n \n if (!this.preloadPoolActive) {\n this.preloadPoolActive = true;\n this.preloadPoolLoop(baseVastUrl);\n }\n \n await this.adPlayer.play();\n\n if (this.expectedAdBreakDurationMs != null && this.adStopTimerId == null) {\n this.scheduleAdStopCountdown(this.getRemainingAdMs());\n }\n\n const adVolume = currentMuted ? 0 : currentVolume;\n this.adPlayer.setAdVolume(adVolume);\n } else {\n await this.enforceGlobalRateLimit();\n this.lastAdRequestTime = Date.now();\n await this.adPlayer.requestAds(firstAdUrl);\n sendAdLoadedTracking(\n this.config.licenseKey,\n { source: \"hls\", vastUrl: firstAdUrl, timestamp: new Date().toISOString() }\n ).catch(() => {});\n\n if (this.config.debugAdTiming) {\n console.log(\"[CONTINUOUS-FETCH] ✅ First ad request successful, starting playback\");\n }\n\n this.consecutiveFailures = 0;\n this.currentAdIndex++;\n this.startContinuousFetching(baseVastUrl);\n \n if (!this.preloadPoolActive) {\n this.startPreloadPool(baseVastUrl, []);\n }\n \n await this.adPlayer.play();\n \n if (this.expectedAdBreakDurationMs != null && this.adStopTimerId == null) {\n this.scheduleAdStopCountdown(this.getRemainingAdMs());\n }\n \n const adVolume = currentMuted ? 0 : currentVolume;\n this.adPlayer.setAdVolume(adVolume);\n }\n } catch (error) {\n if (this.config.debugAdTiming) {\n console.warn(\"[CONTINUOUS-FETCH] ⚠️ First ad request failed:\", error);\n }\n \n if (!usePreloadedAd) {\n const fallbackPreloaded = this.getPreloadedAd();\n if (fallbackPreloaded) {\n if (this.config.debugAdTiming) {\n console.log(\"[CONTINUOUS-FETCH] 🔄 First ad failed, using preloaded fallback\");\n }\n \n try {\n this.adPlayer.destroy();\n this.video.muted = true;\n this.video.volume = 0;\n this.adPlayer = fallbackPreloaded.adController;\n this.attachImaEventListeners();\n \n this.adPlayer.resume();\n \n this.consecutiveFailures = 0;\n this.currentAdIndex++;\n this.startContinuousFetching(baseVastUrl);\n \n if (!this.preloadPoolActive) {\n this.preloadPoolActive = true;\n this.preloadPoolLoop(baseVastUrl);\n }\n \n await this.adPlayer.play();\n \n if (this.expectedAdBreakDurationMs != null && this.adStopTimerId == null) {\n this.scheduleAdStopCountdown(this.getRemainingAdMs());\n }\n \n const adVolume = currentMuted ? 0 : currentVolume;\n this.adPlayer.setAdVolume(adVolume);\n \n return; \n } catch (fallbackError) {\n if (this.config.debugAdTiming) {\n console.warn(\"[CONTINUOUS-FETCH] ⚠️ Preloaded fallback also failed:\", fallbackError);\n }\n }\n }\n }\n \n if (this.isTemporaryAdError(error as Error)) {\n this.temporaryFailureUrls.set(firstAdUrl, Date.now());\n if (this.config.debugAdTiming) {\n console.log(\"[CONTINUOUS-FETCH] First ad had temporary error (no-fill) - will try alternatives\");\n }\n } else {\n this.failedVastUrls.add(firstAdUrl);\n if (this.config.debugAdTiming) {\n console.log(\"[CONTINUOUS-FETCH] First ad had permanent error - URL blacklisted\");\n }\n }\n this.consecutiveFailures++;\n \n this.startContinuousFetching(baseVastUrl);\n await this.tryNextAvailableAdWithRateLimit();\n }\n }\n\n private continuousFetchLoopRunning = false;\n\n private startContinuousFetching(baseVastUrl: string): void {\n if (!this.continuousFetchingActive) {\n return;\n }\n\n if (this.continuousFetchLoopRunning) {\n if (this.config.debugAdTiming) {\n console.log(\"[CONTINUOUS-FETCH] ⏭️ Fetch loop already running, skipping duplicate start\");\n }\n return;\n }\n\n if (this.config.debugAdTiming) {\n console.log(\"[CONTINUOUS-FETCH] 🔄 Starting continuous ad fetching loop\");\n }\n\n this.continuousFetchLoopRunning = true;\n this.continuousFetchLoop(baseVastUrl);\n }\n\n private async continuousFetchLoop(baseVastUrl: string): Promise<void> {\n while (this.continuousFetchingActive && this.inAdBreak) {\n const remaining = this.getRemainingAdMs();\n \n if (remaining <= 0) {\n if (this.config.debugAdTiming) {\n console.log(\"[CONTINUOUS-FETCH] ⏹️ Ad break time expired, stopping URL generation\");\n }\n break;\n }\n\n if (this.isGamInCooldown()) {\n if (this.config.debugAdTiming) {\n console.log(\"[CIRCUIT-BREAKER] GAM in cooldown, stopping URL generation\");\n }\n break;\n }\n\n if (this.consecutiveFailures >= this.maxConsecutiveFailures) {\n if (this.config.debugAdTiming) {\n console.log(`[CONTINUOUS-FETCH] 🛑 Too many consecutive failures (${this.consecutiveFailures}), stopping URL generation`);\n }\n break;\n }\n\n if (this.totalAdRequestsInBreak >= this.maxTotalAdRequestsPerBreak) {\n if (this.config.debugAdTiming) {\n console.log(`[CONTINUOUS-FETCH] 🛑 Maximum ad requests reached (${this.maxTotalAdRequestsPerBreak}), stopping`);\n }\n break;\n }\n\n const maxQueueSize = 5;\n if (this.adRequestQueue.length >= maxQueueSize) {\n if (this.config.debugAdTiming) {\n console.log(`[CONTINUOUS-FETCH] ⏸️ URL queue full (${this.adRequestQueue.length}), waiting...`);\n }\n await new Promise(resolve => setTimeout(resolve, 1000));\n continue;\n }\n\n const newAdUrl = this.generateVastUrlsWithCorrelators(baseVastUrl, 1)[0];\n \n if (!newAdUrl || this.failedVastUrls.has(newAdUrl) || this.isUrlInCooldown(newAdUrl)) {\n await new Promise(resolve => setTimeout(resolve, 500));\n continue;\n }\n\n if (this.config.debugAdTiming) {\n const queuedUrlsPreview = [...this.adRequestQueue, newAdUrl];\n console.log(\n `[CONTINUOUS-FETCH] 📝 Queued VAST URL (queue size: ${queuedUrlsPreview.length})`,\n { queuedUrls: queuedUrlsPreview }\n );\n }\n \n this.adRequestQueue.push(newAdUrl);\n this.totalAdsInBreak++;\n \n const generationDelay = this.consecutiveFailures > 0 \n ? Math.min(1000 * Math.pow(2, this.consecutiveFailures), 5000)\n : 500;\n await new Promise(resolve => setTimeout(resolve, generationDelay));\n }\n\n this.continuousFetchLoopRunning = false;\n\n if (this.config.debugAdTiming) {\n console.log(\n `[CONTINUOUS-FETCH] 🛑 URL generation loop ended (queued: ${this.adRequestQueue.length})`,\n this.adRequestQueue.length > 0 ? { queuedUrls: [...this.adRequestQueue] } : {}\n );\n }\n }\n\n private stopContinuousFetching(): void {\n this.continuousFetchingActive = false;\n this.continuousFetchLoopRunning = false;\n \n this.hidePlaceholderLayer();\n \n if (this.config.debugAdTiming) {\n console.log(\"[CONTINUOUS-FETCH] 🛑 Stopping continuous ad fetching\");\n }\n }\n\n private async tryNextAvailableAdWithRateLimit(): Promise<void> {\n if (this.consecutiveFailures >= this.maxConsecutiveFailures) {\n if (this.config.debugAdTiming) {\n console.log(`[CONTINUOUS-FETCH] 🛑 Too many consecutive failures (${this.consecutiveFailures}), ending ad break gracefully`);\n }\n this.handleAdPodComplete();\n return;\n }\n\n const backoffMultiplier = Math.pow(2, this.consecutiveFailures);\n const backoffDelay = Math.min(this.backoffBaseMs * backoffMultiplier, this.maxBackoffMs);\n const effectiveMinInterval = this.minAdRequestIntervalMs + (this.consecutiveFailures > 0 ? backoffDelay : 0);\n \n const timeSinceLastRequest = Date.now() - this.lastAdRequestTime;\n if (timeSinceLastRequest < effectiveMinInterval) {\n const waitTime = effectiveMinInterval - timeSinceLastRequest;\n if (this.config.debugAdTiming) {\n console.log(`[CONTINUOUS-FETCH] ⏳ Rate limiting: waiting ${waitTime}ms before next request (backoff: ${this.consecutiveFailures} failures)`);\n }\n await new Promise(resolve => setTimeout(resolve, waitTime));\n }\n\n return this.tryNextAvailableAd(0);\n }\n\n private async tryNextAvailableAd(retryCount: number = 0): Promise<void> {\n const remaining = this.getRemainingAdMs();\n \n if (remaining <= 500) {\n if (this.config.debugAdTiming) {\n console.log(\"[CONTINUOUS-FETCH] ⏹️ No time remaining, ending ad break\");\n }\n this.handleAdPodComplete();\n return;\n }\n\n if (this.isGamInCooldown()) {\n if (this.config.debugAdTiming) {\n console.log(\"[CIRCUIT-BREAKER] GAM in cooldown, ending ad break gracefully\");\n }\n this.handleAdPodComplete();\n return;\n }\n\n if (this.consecutiveFailures >= this.maxConsecutiveFailures) {\n if (this.config.debugAdTiming) {\n console.log(`[CONTINUOUS-FETCH] 🛑 Too many consecutive failures (${this.consecutiveFailures}), ending ad break`);\n }\n this.handleAdPodComplete();\n return;\n }\n\n this.cleanupTemporaryFailures();\n\n const preloaded = this.getPreloadedAd();\n if (preloaded) {\n if (this.config.debugAdTiming) {\n console.log(`[CONTINUOUS-FETCH] 🎯 Using preloaded ad from pool (${this.preloadPool.length} remaining in pool)`);\n }\n \n sendAdLoadedTracking(\n this.config.licenseKey,\n { source: \"hls\", vastUrl: preloaded.vastUrl, timestamp: new Date().toISOString() }\n ).catch(() => {});\n\n try {\n this.adPlayer.destroy();\n this.video.muted = true;\n this.video.volume = 0;\n this.adPlayer = preloaded.adController;\n this.attachImaEventListeners();\n\n this.adPlayer.resume();\n\n this.currentAdIndex++;\n this.totalAdRequestsInBreak++;\n this.lastAdRequestTime = Date.now();\n \n await this.adPlayer.play();\n \n if (this.expectedAdBreakDurationMs != null && this.adStopTimerId == null) {\n this.scheduleAdStopCountdown(this.getRemainingAdMs());\n }\n \n const currentMuted = this.video.muted;\n const currentVolume = this.video.volume;\n const adVolume = currentMuted ? 0 : currentVolume;\n this.adPlayer.setAdVolume(adVolume);\n \n this.consecutiveFailures = 0;\n return;\n } catch (error) {\n if (this.config.debugAdTiming) {\n console.warn(\"[CONTINUOUS-FETCH] ⚠️ Preloaded ad failed to play:\", error);\n }\n }\n }\n\n while (this.adRequestQueue.length > 0) {\n const nextAdUrl = this.adRequestQueue.shift();\n \n if (!nextAdUrl) {\n continue;\n }\n \n if (this.failedVastUrls.has(nextAdUrl)) {\n if (this.config.debugAdTiming) {\n console.log(\"[CONTINUOUS-FETCH] ⏭️ Skipping permanently-failed URL, trying next...\");\n }\n continue;\n }\n \n if (this.isUrlInCooldown(nextAdUrl)) {\n if (this.config.debugAdTiming) {\n console.log(\"[CONTINUOUS-FETCH] ⏭️ Skipping URL in cooldown (recent no-fill), trying next...\");\n }\n continue;\n }\n \n if (this.config.debugAdTiming) {\n console.log(`[CONTINUOUS-FETCH] 🎬 Requesting next ad via HLS ad player (${this.currentAdIndex + 1}/${this.totalAdsInBreak}, ${this.adRequestQueue.length} remaining in queue)`);\n }\n \n const currentMuted = this.video.muted;\n const currentVolume = this.video.volume;\n this.adPlayer.updateOriginalMutedState(currentMuted, currentVolume);\n \n this.currentAdIndex++;\n this.totalAdRequestsInBreak++;\n this.lastAdRequestTime = Date.now();\n \n try {\n await this.playSingleAd(nextAdUrl);\n this.consecutiveFailures = 0;\n } catch (error) {\n const errorMessage = (error as Error).message;\n if (this.config.debugAdTiming) {\n console.log(\"[CONTINUOUS-FETCH] ❌ Ad request failed:\", errorMessage);\n }\n \n if (!errorMessage.includes(\"permanently failed\") && !errorMessage.includes(\"in cooldown\")) {\n this.consecutiveFailures++;\n }\n \n await this.tryNextAvailableAdWithRateLimit();\n }\n return;\n }\n\n const maxRetries = 3;\n if (this.continuousFetchingActive && retryCount < maxRetries && remaining > 2000) {\n if (this.config.debugAdTiming) {\n console.log(`[CONTINUOUS-FETCH] ⏳ Queue empty, waiting for URLs... (${retryCount + 1}/${maxRetries})`);\n }\n \n await new Promise(resolve => setTimeout(resolve, 500));\n await this.tryNextAvailableAd(retryCount + 1);\n return;\n }\n\n if (!this.isShowingPlaceholder && remaining > 1000) {\n this.showPlaceholderAndWaitForAds();\n } else {\n if (this.config.debugAdTiming) {\n console.log(\"[CONTINUOUS-FETCH] ⏹️ No more ads available, ending ad break\");\n }\n this.handleAdPodComplete();\n }\n }\n\n private async showPlaceholderAndWaitForAds(): Promise<void> {\n const remaining = this.getRemainingAdMs();\n const waitTime = Math.min(this.maxPlaceholderDurationMs, remaining);\n\n if (this.isGamInCooldown()) {\n if (this.config.debugAdTiming) {\n console.log(\"[CIRCUIT-BREAKER] GAM in cooldown, skipping placeholder wait\");\n }\n this.handleAdPodComplete();\n return;\n }\n \n if (this.consecutiveFailures >= this.maxConsecutiveFailures) {\n if (this.config.debugAdTiming) {\n console.log(\"[CONTINUOUS-FETCH] 🛑 Skipping placeholder - too many consecutive failures\");\n }\n this.handleAdPodComplete();\n return;\n }\n \n if (waitTime < 1000) {\n this.handleAdPodComplete();\n return;\n }\n\n if (this.config.debugAdTiming) {\n console.log(`[CONTINUOUS-FETCH] ⬛ Showing placeholder for ${waitTime}ms while waiting for ad URLs`);\n }\n\n this.isShowingPlaceholder = true;\n \n this.adPlayer.showPlaceholder();\n\n const checkInterval = 300;\n const maxChecks = Math.floor(waitTime / checkInterval);\n \n for (let i = 0; i < maxChecks; i++) {\n await new Promise(resolve => setTimeout(resolve, checkInterval));\n \n if (!this.inAdBreak) {\n return;\n }\n \n if (this.consecutiveFailures >= this.maxConsecutiveFailures) {\n if (this.config.debugAdTiming) {\n console.log(\"[CONTINUOUS-FETCH] 🛑 Too many failures during placeholder wait\");\n }\n break;\n }\n\n while (this.adRequestQueue.length > 0) {\n const nextAdUrl = this.adRequestQueue.shift();\n \n if (!nextAdUrl) {\n continue;\n }\n \n if (this.failedVastUrls.has(nextAdUrl)) {\n continue;\n }\n \n if (this.isUrlInCooldown(nextAdUrl)) {\n continue;\n }\n \n if (this.config.debugAdTiming) {\n console.log(\"[CONTINUOUS-FETCH] ✅ Ad URL available, requesting via HLS ad player\");\n }\n \n this.isShowingPlaceholder = false;\n this.adPlayer.hidePlaceholder();\n \n const currentMuted = this.video.muted;\n const currentVolume = this.video.volume;\n this.adPlayer.updateOriginalMutedState(currentMuted, currentVolume);\n \n this.currentAdIndex++;\n this.totalAdRequestsInBreak++;\n this.lastAdRequestTime = Date.now();\n \n try {\n await this.playSingleAd(nextAdUrl);\n this.consecutiveFailures = 0;\n } catch (error) {\n const errorMessage = (error as Error).message;\n if (!errorMessage.includes(\"permanently failed\") && !errorMessage.includes(\"in cooldown\")) {\n this.consecutiveFailures++;\n }\n await this.tryNextAvailableAdWithRateLimit();\n }\n return;\n }\n }\n\n if (this.config.debugAdTiming) {\n console.log(\"[CONTINUOUS-FETCH] ⏰ Placeholder timeout, ending ad break\");\n }\n \n this.isShowingPlaceholder = false;\n this.adPlayer.hidePlaceholder();\n this.handleAdPodComplete();\n }\n\n private findCurrentOrNextBreak(nowMs: number): AdBreak | undefined {\n const schedule: AdBreak[] = this.vmapBreaks;\n let candidate: AdBreak | undefined;\n for (const b of schedule) {\n if (this.consumedVmapBreakIds.has(this.getAdBreakKey(b))) {\n continue;\n }\n const breakStartMs = this.resolveBreakStartMs(b);\n if (breakStartMs == null) {\n continue;\n }\n const tol = this.config.driftToleranceMs ?? 1000;\n if (\n breakStartMs <= nowMs + tol &&\n (candidate == null ||\n breakStartMs > (this.resolveBreakStartMs(candidate) ?? 0))\n ) {\n candidate = b;\n }\n }\n return candidate;\n }\n\n private onTimeUpdate(currentTimeSec: number): void {\n if (this.adPlayer.isAdPlaying() || this.inAdBreak) return;\n const nowMs = currentTimeSec * 1000;\n const breakToPlay = this.findBreakForTime(nowMs);\n if (breakToPlay) {\n void this.handleMidAdJoin(breakToPlay, nowMs).catch((error) => {\n if (this.config.debugAdTiming) {\n console.warn(\n \"[StormcloudVideoPlayer] Mid-roll VMAP join failed gracefully:\",\n error\n );\n }\n });\n }\n }\n\n private async handleMidAdJoin(\n adBreak: AdBreak,\n nowMs: number\n ): Promise<void> {\n const key = this.getAdBreakKey(adBreak);\n if (this.consumedVmapBreakIds.has(key)) {\n return;\n }\n\n const breakStartMs = this.resolveBreakStartMs(adBreak);\n if (breakStartMs == null) {\n return;\n }\n\n const durationMs = adBreak.durationMs ?? 0;\n const endMs = breakStartMs + durationMs;\n const tol = this.config.driftToleranceMs ?? 1000;\n const inWindow =\n durationMs > 0\n ? nowMs > breakStartMs && nowMs < endMs\n : nowMs + tol >= breakStartMs;\n\n if (inWindow) {\n this.consumedVmapBreakIds.add(key);\n const remainingMs =\n durationMs > 0 ? Math.max(0, endMs - nowMs) : 0;\n const tags =\n this.selectVastTagsForBreak(adBreak) ||\n (this.apiVastTagUrl ? [this.apiVastTagUrl] : undefined);\n if (tags && tags.length > 0) {\n const first = tags[0] as string;\n const rest = tags.slice(1);\n this.adPodQueue = rest;\n \n this.adPlayer.updateOriginalMutedState(this.video.muted, this.video.volume);\n\n try {\n await this.playSingleAd(first);\n this.inAdBreak = true;\n this.expectedAdBreakDurationMs = remainingMs;\n this.currentAdBreakStartWallClockMs = Date.now();\n this.scheduleAdStopCountdown(remainingMs);\n } catch (error) {\n // Keep runtime stable when VMAP break has no-fill/timeouts.\n this.adPodQueue = [];\n if (this.config.debugAdTiming) {\n console.warn(\n \"[StormcloudVideoPlayer] Mid-roll VMAP ad request failed:\",\n error\n );\n }\n }\n }\n }\n }\n\n private scheduleAdStopCountdown(remainingMs: number): void {\n this.clearAdStopTimer();\n const ms = Math.max(0, Math.floor(remainingMs));\n if (ms === 0) {\n this.ensureAdStoppedByTimer();\n return;\n }\n this.adStopTimerId = window.setTimeout(() => {\n this.ensureAdStoppedByTimer();\n }, ms) as unknown as number;\n }\n\n private clearAdStopTimer(): void {\n if (this.adStopTimerId != null) {\n clearTimeout(this.adStopTimerId);\n this.adStopTimerId = undefined;\n }\n }\n\n private ensureAdStoppedByTimer(): void {\n if (!this.inAdBreak) return;\n\n this.adStopTimerId = undefined;\n\n const adPlaying = this.adPlayer.isAdPlaying();\n const pendingAds = this.adPodQueue.length > 0;\n const checkIntervalMs = Math.max(\n 250,\n Math.floor(this.config.adBreakCheckIntervalMs ?? 1000)\n );\n const maxExtensionMsConfig = this.config.maxAdBreakExtensionMs;\n const maxExtensionMs =\n typeof maxExtensionMsConfig === \"number\" && maxExtensionMsConfig > 0\n ? maxExtensionMsConfig\n : 60000;\n\n let elapsedSinceStartMs = 0;\n if (this.currentAdBreakStartWallClockMs != null) {\n elapsedSinceStartMs = Date.now() - this.currentAdBreakStartWallClockMs;\n }\n const expectedDurationMs = this.expectedAdBreakDurationMs ?? 0;\n const overrunMs = Math.max(0, elapsedSinceStartMs - expectedDurationMs);\n\n const shouldExtendAdBreak =\n (adPlaying || pendingAds || this.showAds) && overrunMs < maxExtensionMs;\n\n if (shouldExtendAdBreak) {\n this.scheduleAdStopCountdown(checkIntervalMs);\n return;\n }\n\n if (adPlaying) {\n this.adPlayer.stop().catch(() => {});\n }\n\n this.handleAdPodComplete();\n }\n\n private scheduleAdStartIn(\n delayMs: number,\n marker: Scte35Marker = { type: \"start\" } as Scte35Marker,\n cueKey?: string\n ): void {\n this.clearAdStartTimer();\n const ms = Math.max(0, Math.floor(delayMs));\n if (ms === 0) {\n this.startScte35AdBreak(\n marker,\n cueKey,\n marker.durationSeconds != null ? marker.durationSeconds * 1000 : undefined\n );\n return;\n }\n this.adStartTimerId = window.setTimeout(() => {\n this.startScte35AdBreak(\n marker,\n cueKey,\n marker.durationSeconds != null ? marker.durationSeconds * 1000 : this.expectedAdBreakDurationMs\n );\n }, ms) as unknown as number;\n }\n\n private clearAdStartTimer(): void {\n if (this.adStartTimerId != null) {\n clearTimeout(this.adStartTimerId);\n this.adStartTimerId = undefined;\n }\n }\n\n private updatePtsDrift(ptsSecondsSample: number): void {\n const sampleMs = (this.video.currentTime - ptsSecondsSample) * 1000;\n if (!Number.isFinite(sampleMs) || Math.abs(sampleMs) > 60000) return;\n const alpha = 0.1;\n this.ptsDriftEmaMs = this.ptsDriftEmaMs * (1 - alpha) + sampleMs * alpha;\n }\n\n private isTemporaryAdError(error: Error): boolean {\n const message = error?.message?.toLowerCase() || \"\";\n \n if (message.includes(\"no ads available\") || message.includes(\"no fill\") || message.includes(\"nofill\")) {\n return true;\n }\n \n if (message.includes(\"timeout\")) {\n return true;\n }\n \n if (message.includes(\"rate limit\") || message.includes(\"too many requests\")) {\n return true;\n }\n \n if (message.includes(\"ad playback error\")) {\n return true;\n }\n \n return false;\n }\n\n private isUrlInCooldown(vastTagUrl: string): boolean {\n const failureTime = this.temporaryFailureUrls.get(vastTagUrl);\n if (failureTime == null) {\n return false;\n }\n \n const elapsed = Date.now() - failureTime;\n if (elapsed >= this.temporaryFailureCooldownMs) {\n this.temporaryFailureUrls.delete(vastTagUrl);\n return false;\n }\n \n return true;\n }\n\n private cleanupTemporaryFailures(): void {\n const now = Date.now();\n for (const [url, timestamp] of this.temporaryFailureUrls) {\n if (now - timestamp >= this.temporaryFailureCooldownMs) {\n this.temporaryFailureUrls.delete(url);\n }\n }\n }\n\n private isGamInCooldown(): boolean {\n return Date.now() < this.globalNoFillCooldownUntil;\n }\n\n private recordGamNoFill(): void {\n this.globalConsecutiveNoFills++;\n\n if (this.globalConsecutiveNoFills >= this.globalNoFillThreshold) {\n const exponent = this.globalConsecutiveNoFills - this.globalNoFillThreshold;\n const backoff = Math.min(\n this.globalNoFillBackoffBaseMs * Math.pow(2, exponent),\n this.globalNoFillBackoffMaxMs\n );\n this.globalNoFillCooldownUntil = Date.now() + backoff;\n\n if (this.config.debugAdTiming) {\n console.log(\n `[CIRCUIT-BREAKER] GAM cooldown activated: ${backoff}ms (${this.globalConsecutiveNoFills} consecutive no-fills)`\n );\n }\n }\n }\n\n private resetGamNoFillCounter(): void {\n if (this.globalConsecutiveNoFills > 0 && this.config.debugAdTiming) {\n console.log(\n `[CIRCUIT-BREAKER] Resetting no-fill counter (was ${this.globalConsecutiveNoFills})`\n );\n }\n this.globalConsecutiveNoFills = 0;\n this.globalNoFillCooldownUntil = 0;\n }\n\n private async enforceGlobalRateLimit(): Promise<void> {\n const now = Date.now();\n const elapsed = now - this.globalLastGamRequestTime;\n if (elapsed < this.globalMinGamIntervalMs) {\n const waitMs = this.globalMinGamIntervalMs - elapsed;\n if (this.config.debugAdTiming) {\n console.log(`[RATE-LIMIT] Waiting ${waitMs}ms before next GAM request`);\n }\n await new Promise(resolve => setTimeout(resolve, waitMs));\n }\n this.globalLastGamRequestTime = Date.now();\n }\n\n private async playSingleAd(vastTagUrl: string): Promise<void> {\n if (this.adPlayer.isAdPlaying()) {\n return;\n }\n\n if (this.failedVastUrls.has(vastTagUrl)) {\n if (this.config.debugAdTiming) {\n console.warn(\"[AD-ERROR] Skipping permanently-failed VAST URL:\", vastTagUrl);\n }\n throw new Error(\"VAST URL permanently failed\");\n }\n\n if (this.isUrlInCooldown(vastTagUrl)) {\n if (this.config.debugAdTiming) {\n console.warn(\"[AD-ERROR] Skipping URL in cooldown (recent no-fill):\", vastTagUrl);\n }\n throw new Error(\"VAST URL in cooldown after no-fill\");\n }\n\n if (this.consecutiveFailures >= this.maxConsecutiveFailures) {\n if (this.config.debugAdTiming) {\n console.warn(\"[AD-ERROR] Too many consecutive failures, not requesting more ads\");\n }\n throw new Error(\"Too many consecutive failures\");\n }\n\n if (this.isGamInCooldown()) {\n if (this.config.debugAdTiming) {\n console.warn(\"[CIRCUIT-BREAKER] GAM in cooldown, skipping ad request\");\n }\n throw new Error(\"GAM in cooldown\");\n }\n\n this.recreateAdController();\n\n const requestToken = ++this.adRequestTokenCounter;\n this.activeAdRequestToken = requestToken;\n \n this.startAdRequestWatchdog(requestToken);\n\n try {\n await this.enforceGlobalRateLimit();\n this.lastAdRequestTime = Date.now();\n await this.adPlayer.requestAds(vastTagUrl);\n sendAdLoadedTracking(\n this.config.licenseKey,\n { source: \"hls\", vastUrl: vastTagUrl, timestamp: new Date().toISOString() }\n ).catch(() => {});\n\n this.clearAdRequestWatchdog();\n\n if (this.activeAdRequestToken !== requestToken) {\n return;\n }\n\n try {\n this.startAdFailsafeTimer(requestToken);\n await this.adPlayer.play();\n \n if (this.expectedAdBreakDurationMs != null && this.adStopTimerId == null) {\n this.scheduleAdStopCountdown(this.getRemainingAdMs());\n }\n \n const currentMuted = this.video.muted;\n const currentVolume = this.video.volume;\n const adVolume = currentMuted ? 0 : currentVolume;\n this.adPlayer.setAdVolume(adVolume);\n \n this.consecutiveFailures = 0;\n this.temporaryFailureUrls.delete(vastTagUrl);\n } catch (playError) {\n if (this.config.debugAdTiming) {\n console.error(\"[AD-ERROR] Failed to play ad:\", playError);\n }\n \n const preloadedFallback = this.getPreloadedAd();\n if (preloadedFallback) {\n if (this.config.debugAdTiming) {\n console.log(\"[AD-ERROR] Play failed, trying preloaded fallback ad\");\n }\n \n try {\n this.clearAdFailsafeTimer();\n this.adPlayer.destroy();\n this.video.muted = true;\n this.video.volume = 0;\n this.adPlayer = preloadedFallback.adController;\n this.attachImaEventListeners();\n \n this.adPlayer.resume();\n \n this.consecutiveFailures = 0;\n this.currentAdIndex++;\n this.totalAdRequestsInBreak++;\n \n await this.adPlayer.play();\n \n if (this.expectedAdBreakDurationMs != null && this.adStopTimerId == null) {\n this.scheduleAdStopCountdown(this.getRemainingAdMs());\n }\n \n const currentMuted = this.video.muted;\n const currentVolume = this.video.volume;\n const adVolume = currentMuted ? 0 : currentVolume;\n this.adPlayer.setAdVolume(adVolume);\n \n return; \n } catch (fallbackError) {\n if (this.config.debugAdTiming) {\n console.warn(\"[AD-ERROR] Preloaded fallback also failed:\", fallbackError);\n }\n }\n }\n \n if (this.isTemporaryAdError(playError as Error)) {\n this.temporaryFailureUrls.set(vastTagUrl, Date.now());\n if (this.config.debugAdTiming) {\n console.log(\"[AD-ERROR] Temporary play error - URL can be retried after cooldown\");\n }\n } else {\n this.failedVastUrls.add(vastTagUrl);\n if (this.config.debugAdTiming) {\n console.log(\"[AD-ERROR] Permanent play error - URL blacklisted\");\n }\n }\n \n this.clearAdFailsafeTimer();\n if (this.activeAdRequestToken === requestToken) {\n this.activeAdRequestToken = null;\n }\n throw playError;\n }\n } catch (error) {\n const errorMessage = (error as Error)?.message || \"\";\n if (this.config.debugAdTiming) {\n console.error(\"[AD-ERROR] Ad request failed:\", errorMessage);\n }\n \n const preloadedFallback = this.getPreloadedAd();\n if (preloadedFallback) {\n if (this.config.debugAdTiming) {\n console.log(\"[AD-ERROR] Request failed, trying preloaded fallback ad\");\n }\n \n try {\n this.clearAdRequestWatchdog();\n this.clearAdFailsafeTimer();\n \n this.adPlayer.destroy();\n this.video.muted = true;\n this.video.volume = 0;\n this.adPlayer = preloadedFallback.adController;\n this.attachImaEventListeners();\n \n this.adPlayer.resume();\n \n this.consecutiveFailures = 0;\n this.currentAdIndex++;\n this.totalAdRequestsInBreak++;\n \n await this.adPlayer.play();\n \n const currentMuted = this.video.muted;\n const currentVolume = this.video.volume;\n const adVolume = currentMuted ? 0 : currentVolume;\n this.adPlayer.setAdVolume(adVolume);\n \n return;\n } catch (fallbackError) {\n if (this.config.debugAdTiming) {\n console.warn(\"[AD-ERROR] Preloaded fallback also failed:\", fallbackError);\n }\n }\n }\n \n if (this.isTemporaryAdError(error as Error)) {\n this.temporaryFailureUrls.set(vastTagUrl, Date.now());\n if (this.config.debugAdTiming) {\n console.log(\"[AD-ERROR] Temporary error (no-fill/timeout) - URL can be retried after cooldown\");\n }\n } else {\n this.failedVastUrls.add(vastTagUrl);\n if (this.config.debugAdTiming) {\n console.log(\"[AD-ERROR] Permanent error - URL blacklisted:\", errorMessage);\n }\n }\n\n this.clearAdRequestWatchdog();\n this.clearAdFailsafeTimer();\n if (this.activeAdRequestToken === requestToken) {\n this.activeAdRequestToken = null;\n }\n\n throw error;\n }\n }\n\n private handleAdPodComplete(): void {\n if (this.config.debugAdTiming) {\n console.log(\"[StormcloudVideoPlayer] 🏁 Ad pod complete - cleaning up\");\n }\n\n this.clearAdRequestWatchdog();\n this.clearAdFailsafeTimer();\n this.activeAdRequestToken = null;\n\n this.stopContinuousFetching();\n this.stopPreloadPool();\n this.clearPendingAdBreak();\n \n if (this.isShowingPlaceholder) {\n this.adPlayer.hidePlaceholder();\n this.isShowingPlaceholder = false;\n }\n\n this.adRequestQueue = [];\n\n this.inAdBreak = false;\n this.adDetectSentForCurrentBreak = false;\n this.activeScte35BreakKey = undefined;\n this.scheduledScte35BreakKey = undefined;\n this.expectedAdBreakDurationMs = undefined;\n this.currentAdBreakStartWallClockMs = undefined;\n this.clearAdStartTimer();\n this.clearAdStopTimer();\n this.adPodQueue = [];\n this.showAds = false;\n this.currentAdIndex = 0;\n this.totalAdsInBreak = 0;\n this.consecutiveFailures = 0;\n this.globalConsecutiveNoFills = 0;\n\n this.adPlayer.stop().catch(() => {});\n\n const restoredMuted = this.adPlayer.getOriginalMutedState();\n const restoredVolume = this.adPlayer.getOriginalVolume();\n\n if (this.video.muted !== restoredMuted) {\n this.video.muted = restoredMuted;\n }\n if (Math.abs(this.video.volume - restoredVolume) > 0.01) {\n this.video.volume = restoredVolume;\n }\n\n if (this.shouldContinueLiveStreamDuringAds()) {\n if (this.video.paused) {\n if (this.config.debugAdTiming) {\n console.log(\"[StormcloudVideoPlayer] Content video paused in live mode after ads, resuming playback\");\n }\n this.video.play()?.catch(() => {});\n } else {\n if (this.config.debugAdTiming) {\n console.log(\"[StormcloudVideoPlayer] Content video already playing in live mode after ads\");\n }\n }\n } else if (this.video.paused) {\n this.video.play()?.catch(() => {});\n }\n }\n\n private handleAdFailure(): void {\n this.consecutiveFailures++;\n this.recordGamNoFill();\n const remaining = this.getRemainingAdMs();\n \n if (this.config.debugAdTiming) {\n console.log(\n `[CONTINUOUS-FETCH] Ad failure: remaining=${remaining}ms, queued ads=${this.adRequestQueue.length}, consecutiveFailures=${this.consecutiveFailures}`,\n this.adRequestQueue.length > 0 ? { queuedUrls: [...this.adRequestQueue] } : {}\n );\n }\n \n if (this.consecutiveFailures >= this.maxConsecutiveFailures) {\n if (this.config.debugAdTiming) {\n console.log(`[CONTINUOUS-FETCH] 🛑 Max consecutive failures reached (${this.consecutiveFailures}), ending ad break gracefully`);\n }\n this.handleAdPodComplete();\n return;\n }\n \n if (remaining > 500) {\n this.tryNextAvailableAdWithRateLimit();\n } else {\n if (this.config.debugAdTiming) {\n console.log(\"[AD-ERROR] Ad failed and no time remaining. Failed URLs:\", this.failedVastUrls.size);\n }\n this.handleAdPodComplete();\n }\n }\n\n private startAdRequestWatchdog(token: number): void {\n this.clearAdRequestWatchdog();\n\n const timeoutMs = this.config.adFailsafeTimeoutMs ?? 10000;\n this.adRequestWatchdogToken = token;\n this.adRequestWatchdogId = window.setTimeout(() => {\n if (this.adRequestWatchdogToken !== token) {\n return;\n }\n\n this.adRequestWatchdogId = undefined;\n this.adRequestWatchdogToken = null;\n if (this.activeAdRequestToken === token) {\n this.activeAdRequestToken = null;\n }\n\n this.logAdState(\"ad_request_timeout\", { token, timeoutMs });\n this.handleAdFailure();\n }, timeoutMs) as unknown as number;\n\n this.logAdState(\"ad_request_watchdog_started\", { token, timeoutMs });\n }\n\n private clearAdRequestWatchdog(): void {\n if (this.adRequestWatchdogId != null) {\n clearTimeout(this.adRequestWatchdogId);\n this.adRequestWatchdogId = undefined;\n }\n\n if (this.adRequestWatchdogToken != null) {\n this.logAdState(\"ad_request_watchdog_cleared\", {\n token: this.adRequestWatchdogToken,\n });\n this.adRequestWatchdogToken = null;\n }\n }\n\n private startAdFailsafeTimer(token: number): void {\n this.clearAdFailsafeTimer();\n\n const failsafeMs = this.config.adFailsafeTimeoutMs ?? 10000;\n this.adFailsafeToken = token;\n\n this.adFailsafeTimerId = window.setTimeout(() => {\n if (this.adFailsafeToken !== token) {\n return;\n }\n\n this.adFailsafeTimerId = undefined;\n this.adFailsafeToken = null;\n\n if (this.activeAdRequestToken === token) {\n this.activeAdRequestToken = null;\n }\n\n this.logAdState(\"ad_failsafe_triggered\", {\n token,\n failsafeMs,\n videoPaused: this.video.paused,\n imaAdPlaying: this.adPlayer.isAdPlaying(),\n });\n\n this.handleAdFailure();\n }, failsafeMs) as unknown as number;\n\n this.logAdState(\"ad_failsafe_started\", { token, failsafeMs });\n }\n\n private clearAdFailsafeTimer(): void {\n if (this.adFailsafeTimerId != null) {\n clearTimeout(this.adFailsafeTimerId);\n this.logAdState(\"ad_failsafe_cleared\", { token: this.adFailsafeToken });\n this.adFailsafeTimerId = undefined;\n }\n\n this.adFailsafeToken = null;\n }\n\n private selectVastTagsForBreak(b?: AdBreak): string[] | undefined {\n if (!b || !b.vastTagUrl) return undefined;\n if (b.vastTagUrl.includes(\",\")) {\n return b.vastTagUrl\n .split(\",\")\n .map((s) => s.trim())\n .filter((s) => s.length > 0);\n }\n return [b.vastTagUrl];\n }\n\n private logAdState(event: string, extra: Record<string, unknown> = {}): void {\n if (!this.config.debugAdTiming) {\n return;\n }\n\n console.log(\"[StormcloudVideoPlayer][AdState]\", {\n event,\n timestamp: new Date().toISOString(),\n showAds: this.showAds,\n adPlaying: this.adPlayer.isAdPlaying(),\n inAdBreak: this.inAdBreak,\n activeAdRequestToken: this.activeAdRequestToken,\n ...extra,\n });\n }\n\n private getRemainingAdMs(): number {\n if (\n this.expectedAdBreakDurationMs == null ||\n this.currentAdBreakStartWallClockMs == null\n )\n return 0;\n const elapsed = Date.now() - this.currentAdBreakStartWallClockMs;\n return Math.max(0, this.expectedAdBreakDurationMs - elapsed);\n }\n\n private findBreakForTime(nowMs: number): AdBreak | undefined {\n const schedule: AdBreak[] = this.vmapBreaks;\n const tol = this.config.driftToleranceMs ?? 1000;\n for (const b of schedule) {\n if (this.consumedVmapBreakIds.has(this.getAdBreakKey(b))) {\n continue;\n }\n const breakStartMs = this.resolveBreakStartMs(b);\n if (breakStartMs == null) {\n continue;\n }\n const end = breakStartMs + (b.durationMs || 0);\n if (\n nowMs >= breakStartMs &&\n (b.durationMs ? nowMs < end : nowMs <= breakStartMs + tol)\n ) {\n return b;\n }\n }\n return undefined;\n }\n\n toggleMute(): void {\n if (this.adPlayer.isAdPlaying()) {\n const currentPerceptualState = this.isMuted();\n const newMutedState = !currentPerceptualState;\n\n this.adPlayer.updateOriginalMutedState(newMutedState, this.video.volume);\n this.adPlayer.setAdVolume(newMutedState ? 0 : 1);\n\n if (this.config.debugAdTiming) {\n console.log(\n \"[StormcloudVideoPlayer] Mute toggle during ad - immediately applied:\",\n newMutedState\n );\n }\n } else {\n this.video.muted = !this.video.muted;\n this.adPlayer.updateOriginalMutedState(this.video.muted, this.video.volume);\n if (this.config.debugAdTiming) {\n console.log(\"[StormcloudVideoPlayer] Muted:\", this.video.muted);\n }\n }\n }\n\n toggleFullscreen(): Promise<void> {\n return new Promise((resolve, reject) => {\n if (!document.fullscreenElement) {\n const container = this.video.parentElement;\n if (!container) {\n reject(new Error(\"No parent container found for fullscreen\"));\n return;\n }\n container\n .requestFullscreen()\n .then(() => {\n if (this.config.debugAdTiming) {\n console.log(\"[StormcloudVideoPlayer] Entered fullscreen\");\n }\n resolve();\n })\n .catch((err) => {\n if (this.config.debugAdTiming) {\n console.error(\"[StormcloudVideoPlayer] Fullscreen error:\", err);\n }\n reject(err);\n });\n } else {\n document\n .exitFullscreen()\n .then(() => {\n if (this.config.debugAdTiming) {\n console.log(\"[StormcloudVideoPlayer] Exited fullscreen\");\n }\n resolve();\n })\n .catch((err) => {\n if (this.config.debugAdTiming) {\n console.error(\n \"[StormcloudVideoPlayer] Exit fullscreen error:\",\n err\n );\n }\n reject(err);\n });\n }\n });\n }\n\n isMuted(): boolean {\n if (this.adPlayer.isAdPlaying()) {\n if (this.config.debugAdTiming) {\n console.log(\n \"[StormcloudVideoPlayer] isMuted() override during ad playback -> false\"\n );\n }\n return false;\n }\n return this.video.muted;\n }\n\n setMuted(muted: boolean): void {\n const adPlaying = this.adPlayer.isAdPlaying();\n\n if (adPlaying && muted === this.video.muted) {\n if (this.config.debugAdTiming) {\n console.log(\n \"[StormcloudVideoPlayer] setMuted reflective update during ad ignored\",\n { muted }\n );\n }\n return;\n }\n\n this.video.muted = muted;\n\n if (adPlaying) {\n this.adPlayer.updateOriginalMutedState(muted, this.video.volume);\n this.adPlayer.setAdVolume(muted ? 0 : 1);\n if (this.config.debugAdTiming) {\n console.log(\"[StormcloudVideoPlayer] setMuted applied during ad\", {\n muted,\n });\n }\n return;\n }\n\n this.adPlayer.updateOriginalMutedState(muted, this.video.volume);\n if (this.config.debugAdTiming) {\n console.log(\"[StormcloudVideoPlayer] setMuted called:\", muted);\n }\n }\n\n setVolume(volume: number): void {\n const clampedVolume = Math.max(0, Math.min(1, volume));\n const adPlaying = this.adPlayer.isAdPlaying();\n\n if (adPlaying) {\n this.adPlayer.setAdVolume(clampedVolume);\n this.adPlayer.updateOriginalMutedState(clampedVolume === 0, clampedVolume);\n if (this.config.debugAdTiming) {\n console.log(\"[StormcloudVideoPlayer] setVolume applied during ad\", {\n volume: clampedVolume,\n });\n }\n } else {\n this.video.volume = clampedVolume;\n this.video.muted = clampedVolume === 0;\n this.adPlayer.updateOriginalMutedState(clampedVolume === 0, clampedVolume);\n if (this.config.debugAdTiming) {\n console.log(\"[StormcloudVideoPlayer] setVolume called:\", clampedVolume);\n }\n }\n }\n\n getVolume(): number {\n const adPlaying = this.adPlayer.isAdPlaying();\n if (adPlaying) {\n return this.adPlayer.getAdVolume();\n }\n return this.video.volume;\n }\n\n isFullscreen(): boolean {\n return !!document.fullscreenElement;\n }\n\n isLive(): boolean {\n return this.isLiveStream;\n }\n\n get videoElement(): HTMLVideoElement {\n return this.video;\n }\n\n resize(): void {\n if (this.config.debugAdTiming) {\n console.log(\"[StormcloudVideoPlayer] Resizing player\");\n }\n\n if (this.adPlayer && this.adPlayer.isAdPlaying()) {\n const width = this.video.clientWidth || 640;\n const height = this.video.clientHeight || 480;\n\n if (this.config.debugAdTiming) {\n console.log(\n `[StormcloudVideoPlayer] Resizing ads manager to ${width}x${height}`\n );\n }\n\n this.adPlayer.resize(width, height);\n }\n }\n\n destroy(): void {\n this.stopContinuousFetching();\n this.stopPreloadPool();\n this.clearAdStartTimer();\n this.clearAdStopTimer();\n this.clearAdFailsafeTimer();\n this.clearAdRequestWatchdog();\n this.clearPendingAdBreak();\n \n if (this.placeholderContainer) {\n if (this.placeholderContainer.parentElement) {\n this.placeholderContainer.parentElement.removeChild(this.placeholderContainer);\n }\n this.placeholderContainer = undefined;\n }\n \n if (this.timeUpdateHandler) {\n this.video.removeEventListener(\"timeupdate\", this.timeUpdateHandler);\n delete this.timeUpdateHandler;\n }\n if (this.emptiedHandler) {\n this.video.removeEventListener(\"emptied\", this.emptiedHandler);\n delete this.emptiedHandler;\n }\n \n if (this.heartbeatInterval) {\n clearInterval(this.heartbeatInterval);\n this.heartbeatInterval = undefined;\n }\n this.hls?.destroy();\n this.adPlayer?.destroy();\n\n if (this.palPlaybackStarted) {\n this.palPlaybackStarted = false;\n this.palNonce.sendPlaybackEnd();\n }\n this.palNonce.reset();\n\n this.adRequestQueue = [];\n this.consecutiveFailures = 0;\n }\n}\n","import type { AdController } from \"../types\";\nimport Hls from \"hls.js\";\n\ninterface VastMediaFile {\n url: string;\n type: string;\n width: number;\n height: number;\n bitrate?: number | undefined;\n}\n\ninterface VastTrackingUrls {\n impression: string[];\n start: string[];\n firstQuartile: string[];\n midpoint: string[];\n thirdQuartile: string[];\n complete: string[];\n mute: string[];\n unmute: string[];\n pause: string[];\n resume: string[];\n fullscreen: string[];\n exitFullscreen: string[];\n skip: string[];\n error: string[];\n}\n\ninterface VastAd {\n id: string;\n title: string;\n duration: number;\n mediaFiles: VastMediaFile[];\n trackingUrls: VastTrackingUrls;\n clickThrough?: string | undefined;\n}\n\nexport function createHlsAdPlayer(\n contentVideo: HTMLVideoElement,\n options?: {\n continueLiveStreamDuringAds?: boolean;\n licenseKey?: string;\n mainHlsInstance?: Hls;\n }\n): AdController {\n let adPlaying = false;\n let originalMutedState = false;\n let originalVolume = Math.max(0, Math.min(1, contentVideo.volume || 1));\n const listeners = new Map<string, Set<(payload?: any) => void>>();\n const licenseKey = options?.licenseKey;\n const mainHlsInstance = options?.mainHlsInstance;\n\n let adVideoElement: HTMLVideoElement | undefined;\n let adHls: Hls | undefined;\n let adContainerEl: HTMLDivElement | undefined;\n let currentAd: VastAd | undefined;\n let sessionId: string | undefined;\n const preloadedAds = new Map<string, VastAd>();\n const preloadingAds = new Map<string, Promise<void>>();\n let destroyed = false;\n let pendingTimeouts: number[] = [];\n\n let trackingFired = {\n impression: false,\n start: false,\n firstQuartile: false,\n midpoint: false,\n thirdQuartile: false,\n complete: false,\n };\n\n function emit(event: string, payload?: any): void {\n const set = listeners.get(event);\n if (!set) return;\n for (const fn of Array.from(set)) {\n try {\n fn(payload);\n } catch (error) {\n console.warn(\n `[HlsAdPlayer] Error in event listener for ${event}:`,\n error\n );\n }\n }\n }\n\n function generateSessionId(): string {\n return `session-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;\n }\n\n function fireTrackingPixels(urls: string[]): void {\n if (!urls || urls.length === 0) return;\n\n urls.forEach((url) => {\n try {\n let trackingUrl = url;\n\n if (sessionId) {\n trackingUrl = `${trackingUrl}${\n trackingUrl.includes(\"?\") ? \"&\" : \"?\"\n }session_id=${sessionId}`;\n }\n\n if (licenseKey) {\n trackingUrl = `${trackingUrl}${\n trackingUrl.includes(\"?\") ? \"&\" : \"?\"\n }license_key=${licenseKey}`;\n }\n\n const img = new Image(1, 1);\n img.src = trackingUrl;\n console.log(`[HlsAdPlayer] Fired tracking pixel: ${trackingUrl}`);\n } catch (error) {\n console.warn(`[HlsAdPlayer] Error firing tracking pixel:`, error);\n }\n });\n }\n\n function getMainStreamQuality(): {\n width: number;\n height: number;\n bitrate: number;\n } | null {\n if (!mainHlsInstance || !mainHlsInstance.levels) {\n return null;\n }\n\n const currentLevel = mainHlsInstance.currentLevel;\n if (currentLevel === -1 || !mainHlsInstance.levels[currentLevel]) {\n const autoLevel = mainHlsInstance.loadLevel;\n if (autoLevel !== -1 && mainHlsInstance.levels[autoLevel]) {\n const level = mainHlsInstance.levels[autoLevel];\n return {\n width: level.width || 1920,\n height: level.height || 1080,\n bitrate: level.bitrate || 5000000,\n };\n }\n return null;\n }\n\n const level = mainHlsInstance.levels[currentLevel];\n return {\n width: level.width || 1920,\n height: level.height || 1080,\n bitrate: level.bitrate || 5000000,\n };\n }\n\n function selectBestMediaFile(mediaFiles: VastMediaFile[]): VastMediaFile {\n if (mediaFiles.length === 0) {\n throw new Error(\"No media files available\");\n }\n\n const firstFile = mediaFiles[0];\n if (!firstFile) {\n throw new Error(\"No media files available\");\n }\n\n if (mediaFiles.length === 1) {\n return firstFile;\n }\n\n const mainQuality = getMainStreamQuality();\n if (!mainQuality) {\n console.log(\n \"[HlsAdPlayer] No main stream quality info, using first media file\"\n );\n return firstFile;\n }\n\n console.log(\"[HlsAdPlayer] Main stream quality:\", mainQuality);\n\n const scoredFiles = mediaFiles.map((file) => {\n const widthDiff = Math.abs(file.width - mainQuality.width);\n const heightDiff = Math.abs(file.height - mainQuality.height);\n const resolutionDiff = widthDiff + heightDiff;\n\n const fileBitrate = (file.bitrate || 5000) * 1000;\n const bitrateDiff = Math.abs(fileBitrate - mainQuality.bitrate);\n\n const score = resolutionDiff * 2 + bitrateDiff / 1000;\n\n return { file, score, resolutionDiff, bitrateDiff };\n });\n\n scoredFiles.sort((a, b) => a.score - b.score);\n\n const bestMatch = scoredFiles[0];\n if (!bestMatch) {\n console.log(\"[HlsAdPlayer] No best match found, using first media file\");\n return firstFile;\n }\n\n console.log(\"[HlsAdPlayer] Selected media file:\", {\n url: bestMatch.file.url,\n resolution: `${bestMatch.file.width}x${bestMatch.file.height}`,\n bitrate: bestMatch.file.bitrate,\n score: bestMatch.score,\n resolutionDiff: bestMatch.resolutionDiff,\n bitrateDiff: bestMatch.bitrateDiff,\n });\n\n return bestMatch.file;\n }\n\n function isHlsMediaFile(mediaFile: VastMediaFile): boolean {\n const type = mediaFile.type.toLowerCase();\n const url = mediaFile.url.toLowerCase();\n return (\n type === \"application/x-mpegurl\" ||\n type === \"application/vnd.apple.mpegurl\" ||\n type.includes(\"mpegurl\") ||\n url.includes(\".m3u8\")\n );\n }\n\n function isProgressiveMediaFile(mediaFile: VastMediaFile): boolean {\n const type = mediaFile.type.toLowerCase();\n const url = mediaFile.url.toLowerCase();\n return (\n type.startsWith(\"video/\") ||\n url.endsWith(\".mp4\") ||\n url.includes(\".mp4?\")\n );\n }\n\n function parseVastXml(xmlString: string): VastAd | null {\n try {\n const parser = new DOMParser();\n const xmlDoc = parser.parseFromString(xmlString, \"text/xml\");\n\n const parserError = xmlDoc.querySelector(\"parsererror\");\n if (parserError) {\n console.error(\n \"[HlsAdPlayer] XML parsing error (malformed VAST XML):\",\n parserError.textContent\n );\n return null;\n }\n\n const adElement = xmlDoc.querySelector(\"Ad\");\n if (!adElement) {\n console.warn(\"[HlsAdPlayer] No Ad element found in VAST XML\");\n return null;\n }\n\n const adId = adElement.getAttribute(\"id\") || \"unknown\";\n const title = xmlDoc.querySelector(\"AdTitle\")?.textContent || \"Ad\";\n\n const isNoAdAvailable =\n adId === \"empty\" ||\n title.toLowerCase().includes(\"no ad available\") ||\n title.toLowerCase() === \"no ad available\";\n\n const durationText =\n xmlDoc.querySelector(\"Duration\")?.textContent || \"00:00:30\";\n const durationParts = durationText.split(\":\");\n const duration =\n parseInt(durationParts[0] || \"0\", 10) * 3600 +\n parseInt(durationParts[1] || \"0\", 10) * 60 +\n parseInt(durationParts[2] || \"0\", 10);\n\n const mediaFileElements = xmlDoc.querySelectorAll(\"MediaFile\");\n const mediaFiles: VastMediaFile[] = [];\n\n console.log(\n `[HlsAdPlayer] Found ${mediaFileElements.length} MediaFile element(s) in VAST XML`\n );\n\n mediaFileElements.forEach((mf, index) => {\n const type = mf.getAttribute(\"type\") || \"\";\n const url = mf.textContent?.trim() || \"\";\n const width = mf.getAttribute(\"width\") || \"\";\n const height = mf.getAttribute(\"height\") || \"\";\n\n console.log(\n `[HlsAdPlayer] MediaFile ${index}: type=\"${type}\", url=\"${url}\", width=\"${width}\", height=\"${height}\"`\n );\n\n const mediaFile: VastMediaFile = {\n url,\n type,\n width: parseInt(width || \"1920\", 10),\n height: parseInt(height || \"1080\", 10),\n bitrate: undefined,\n };\n\n if (!url) {\n console.warn(`[HlsAdPlayer] MediaFile ${index} has empty URL`);\n return;\n }\n\n const bitrateAttr = mf.getAttribute(\"bitrate\");\n const bitrateValue = bitrateAttr\n ? parseInt(bitrateAttr, 10)\n : undefined;\n mediaFile.bitrate =\n bitrateValue && bitrateValue > 0 ? bitrateValue : undefined;\n\n if (isHlsMediaFile(mediaFile) || isProgressiveMediaFile(mediaFile)) {\n mediaFiles.push(mediaFile);\n console.log(\n `[HlsAdPlayer] Added ${isHlsMediaFile(mediaFile) ? \"HLS\" : \"progressive\"} MediaFile: ${url}`\n );\n } else {\n console.log(\n `[HlsAdPlayer] MediaFile ${index} ignored (type=\"${type}\" is not supported)`\n );\n }\n });\n\n if (mediaFiles.length === 0) {\n if (isNoAdAvailable) {\n console.warn(\n \"[HlsAdPlayer] No ads available (VAST response indicates no ads)\"\n );\n } else {\n console.warn(\"[HlsAdPlayer] No supported media files found in VAST XML\");\n }\n return null;\n }\n\n const trackingUrls: VastTrackingUrls = {\n impression: [],\n start: [],\n firstQuartile: [],\n midpoint: [],\n thirdQuartile: [],\n complete: [],\n mute: [],\n unmute: [],\n pause: [],\n resume: [],\n fullscreen: [],\n exitFullscreen: [],\n skip: [],\n error: [],\n };\n\n xmlDoc.querySelectorAll(\"Impression\").forEach((el) => {\n const url = el.textContent?.trim();\n if (url) trackingUrls.impression.push(url);\n });\n\n xmlDoc.querySelectorAll(\"Tracking\").forEach((el) => {\n const event = el.getAttribute(\"event\");\n const url = el.textContent?.trim();\n if (event && url) {\n const eventKey = event as keyof VastTrackingUrls;\n if (trackingUrls[eventKey]) {\n trackingUrls[eventKey].push(url);\n }\n }\n });\n\n const clickThrough = xmlDoc\n .querySelector(\"ClickThrough\")\n ?.textContent?.trim();\n\n return {\n id: adId,\n title,\n duration,\n mediaFiles,\n trackingUrls,\n clickThrough,\n };\n } catch (error) {\n console.error(\"[HlsAdPlayer] Error parsing VAST XML:\", error);\n return null;\n }\n }\n\n async function fetchAndParseVastAd(\n vastTagUrl: string\n ): Promise<VastAd | null> {\n const response = await fetch(vastTagUrl, {\n mode: \"cors\",\n credentials: \"include\",\n headers: {\n \"Accept\": \"application/xml, text/xml, */*\",\n },\n referrerPolicy: \"no-referrer-when-downgrade\",\n });\n if (!response.ok) {\n throw new Error(`Failed to fetch VAST: ${response.statusText}`);\n }\n\n const vastXml = await response.text();\n console.log(\"[HlsAdPlayer] VAST XML received\");\n console.log(\n \"[HlsAdPlayer] VAST XML content (first 2000 chars):\",\n vastXml.substring(0, 2000)\n );\n\n return parseVastXml(vastXml);\n }\n\n function createAdVideoElement(): HTMLVideoElement {\n const video = document.createElement(\"video\");\n video.style.position = \"absolute\";\n video.style.left = \"0\";\n video.style.top = \"0\";\n video.style.width = \"100%\";\n video.style.height = \"100%\";\n video.style.objectFit = \"contain\";\n video.style.backgroundColor = \"#000\";\n video.playsInline = true;\n video.muted = false;\n\n video.volume = 1.0;\n console.log(\n `[HlsAdPlayer] Created ad video element with volume ${video.volume}`\n );\n\n return video;\n }\n\n function setupAdEventListeners(): void {\n if (!adVideoElement || !currentAd) return;\n\n adVideoElement.addEventListener(\"timeupdate\", () => {\n if (!currentAd || !adVideoElement) return;\n\n const progress = adVideoElement.currentTime / currentAd.duration;\n\n if (progress >= 0.25 && !trackingFired.firstQuartile) {\n trackingFired.firstQuartile = true;\n fireTrackingPixels(currentAd.trackingUrls.firstQuartile);\n }\n\n if (progress >= 0.5 && !trackingFired.midpoint) {\n trackingFired.midpoint = true;\n fireTrackingPixels(currentAd.trackingUrls.midpoint);\n }\n\n if (progress >= 0.75 && !trackingFired.thirdQuartile) {\n trackingFired.thirdQuartile = true;\n fireTrackingPixels(currentAd.trackingUrls.thirdQuartile);\n }\n });\n\n adVideoElement.addEventListener(\"playing\", () => {\n if (!currentAd || trackingFired.start) return;\n trackingFired.start = true;\n fireTrackingPixels(currentAd.trackingUrls.start);\n console.log(\"[HlsAdPlayer] Ad started playing\");\n });\n\n adVideoElement.addEventListener(\"ended\", () => {\n if (!currentAd || trackingFired.complete) return;\n trackingFired.complete = true;\n fireTrackingPixels(currentAd.trackingUrls.complete);\n console.log(\"[HlsAdPlayer] Ad completed\");\n\n handleAdComplete();\n });\n\n adVideoElement.addEventListener(\"error\", (e) => {\n console.error(\"[HlsAdPlayer] Ad video error:\", e);\n if (currentAd) {\n fireTrackingPixels(currentAd.trackingUrls.error);\n }\n handleAdError();\n });\n\n adVideoElement.addEventListener(\"volumechange\", () => {\n if (!currentAd) return;\n if (adVideoElement!.muted) {\n fireTrackingPixels(currentAd.trackingUrls.mute);\n } else {\n fireTrackingPixels(currentAd.trackingUrls.unmute);\n }\n });\n\n adVideoElement.addEventListener(\"pause\", () => {\n if (currentAd && !adVideoElement!.ended) {\n fireTrackingPixels(currentAd.trackingUrls.pause);\n }\n });\n\n adVideoElement.addEventListener(\"play\", () => {\n if (currentAd && adVideoElement!.currentTime > 0) {\n fireTrackingPixels(currentAd.trackingUrls.resume);\n }\n });\n }\n\n function setAdPlayingFlag(isPlaying: boolean): void {\n if (isPlaying) {\n contentVideo.dataset.stormcloudAdPlaying = \"true\";\n } else {\n delete contentVideo.dataset.stormcloudAdPlaying;\n }\n }\n\n function handleAdComplete(): void {\n console.log(\"[HlsAdPlayer] Handling ad completion\");\n adPlaying = false;\n setAdPlayingFlag(false);\n\n contentVideo.muted = true;\n contentVideo.volume = 0;\n\n if (adContainerEl) {\n adContainerEl.style.display = \"none\";\n adContainerEl.style.pointerEvents = \"none\";\n }\n \n if (options?.continueLiveStreamDuringAds) {\n if (contentVideo.paused) {\n console.log(\"[HlsAdPlayer] Content video paused in live mode, resuming playback\");\n contentVideo.play().catch(() => {});\n } else {\n console.log(\"[HlsAdPlayer] Content video already playing in live mode\");\n }\n }\n\n emit(\"content_resume\");\n }\n\n function handleAdError(): void {\n console.log(\"[HlsAdPlayer] Handling ad error\");\n adPlaying = false;\n setAdPlayingFlag(false);\n\n contentVideo.muted = true;\n contentVideo.volume = 0;\n\n if (adContainerEl) {\n adContainerEl.style.display = \"none\";\n adContainerEl.style.pointerEvents = \"none\";\n }\n\n emit(\"ad_error\");\n }\n\n return {\n initialize() {\n console.log(\"[HlsAdPlayer] Initializing\");\n\n if (!adContainerEl) {\n const container = document.createElement(\"div\");\n container.style.position = \"absolute\";\n container.style.left = \"0\";\n container.style.top = \"0\";\n container.style.right = \"0\";\n container.style.bottom = \"0\";\n container.style.display = \"none\";\n container.style.alignItems = \"center\";\n container.style.justifyContent = \"center\";\n container.style.pointerEvents = \"none\";\n container.style.zIndex = \"30\";\n container.style.backgroundColor = \"#000\";\n\n contentVideo.parentElement?.appendChild(container);\n adContainerEl = container;\n }\n },\n\n async requestAds(vastTagUrl: string) {\n console.log(\"[HlsAdPlayer] Requesting ads:\", vastTagUrl);\n\n if (adPlaying) {\n console.warn(\n \"[HlsAdPlayer] Cannot request new ads while an ad is playing\"\n );\n return Promise.reject(new Error(\"Ad already playing\"));\n }\n\n try {\n sessionId = generateSessionId();\n let ad: VastAd | null | undefined;\n\n if (preloadedAds.has(vastTagUrl)) {\n ad = preloadedAds.get(vastTagUrl);\n preloadedAds.delete(vastTagUrl);\n console.log(\n \"[HlsAdPlayer] Using preloaded VAST response:\",\n vastTagUrl\n );\n } else {\n ad = await fetchAndParseVastAd(vastTagUrl);\n }\n\n if (!ad) {\n console.warn(\"[HlsAdPlayer] No ads available from VAST response\");\n emit(\"ad_error\");\n return Promise.reject(new Error(\"No ads available from VAST response\"));\n }\n\n currentAd = ad;\n console.log(\n `[HlsAdPlayer] Ad parsed: ${ad.title}, duration: ${ad.duration}s`\n );\n\n fireTrackingPixels(ad.trackingUrls.impression);\n trackingFired.impression = true;\n\n return Promise.resolve();\n } catch (error) {\n console.error(\"[HlsAdPlayer] Error requesting ads:\", error);\n emit(\"ad_error\");\n return Promise.reject(error);\n }\n },\n async play() {\n if (!currentAd) {\n console.warn(\n \"[HlsAdPlayer] Cannot play: No ad loaded (no ads available)\"\n );\n return Promise.reject(new Error(\"No ad loaded\"));\n }\n\n console.log(\"[HlsAdPlayer] Starting ad playback\");\n\n try {\n if (!adVideoElement) {\n adVideoElement = createAdVideoElement();\n adContainerEl?.appendChild(adVideoElement);\n setupAdEventListeners();\n }\n\n trackingFired = {\n impression: trackingFired.impression,\n start: false,\n firstQuartile: false,\n midpoint: false,\n thirdQuartile: false,\n complete: false,\n };\n\n const contentVolume = contentVideo.volume;\n originalVolume = Math.max(\n 0,\n Math.min(1, contentVolume || originalVolume)\n );\n\n if (!options?.continueLiveStreamDuringAds) {\n contentVideo.pause();\n console.log(\"[HlsAdPlayer] Content paused (VOD mode)\");\n } else {\n console.log(\"[HlsAdPlayer] Content continues (Live mode)\");\n }\n\n console.log(\"[HlsAdPlayer] FORCE MUTING main video\");\n contentVideo.muted = true;\n contentVideo.volume = 0;\n adPlaying = true;\n setAdPlayingFlag(true);\n\n if (adVideoElement) {\n const adVolume = originalMutedState ? 0 : originalVolume;\n adVideoElement.volume = Math.max(0, Math.min(1, adVolume));\n adVideoElement.muted = false;\n console.log(\n `[HlsAdPlayer] Set ad video volume to ${adVideoElement.volume}, muted: ${adVideoElement.muted}, originalMutedState: ${originalMutedState}, contentVolume: ${contentVolume}`\n );\n }\n\n if (adContainerEl) {\n adContainerEl.style.display = \"flex\";\n adContainerEl.style.pointerEvents = \"auto\";\n }\n\n emit(\"content_pause\");\n\n const mediaFile = selectBestMediaFile(currentAd.mediaFiles);\n if (!mediaFile) {\n throw new Error(\"No media file available for ad\");\n }\n\n const isHlsAd = isHlsMediaFile(mediaFile);\n console.log(\n `[HlsAdPlayer] Loading ${isHlsAd ? \"HLS\" : \"progressive\"} ad from: ${mediaFile.url}`\n );\n\n if (isHlsAd && Hls.isSupported()) {\n if (adHls) {\n adHls.destroy();\n }\n\n adHls = new Hls({\n enableWorker: true,\n lowLatencyMode: false,\n });\n\n adHls.loadSource(mediaFile.url);\n adHls.attachMedia(adVideoElement);\n\n adHls.on(Hls.Events.MANIFEST_PARSED, () => {\n console.log(\"[HlsAdPlayer] HLS manifest parsed, starting playback\");\n adVideoElement!.play().catch((error) => {\n console.error(\"[HlsAdPlayer] Error starting ad playback:\", error);\n handleAdError();\n });\n });\n\n adHls.on(Hls.Events.ERROR, (event, data) => {\n console.error(\"[HlsAdPlayer] HLS error:\", data);\n if (data.fatal) {\n handleAdError();\n }\n });\n } else if (isHlsAd && (\n adVideoElement.canPlayType(\"application/vnd.apple.mpegurl\")\n )) {\n adVideoElement.src = mediaFile.url;\n adVideoElement.play().catch((error) => {\n console.error(\"[HlsAdPlayer] Error starting ad playback:\", error);\n handleAdError();\n });\n } else if (!isHlsAd && isProgressiveMediaFile(mediaFile)) {\n if (adHls) {\n adHls.destroy();\n adHls = undefined;\n }\n\n adVideoElement.src = mediaFile.url;\n adVideoElement.load();\n adVideoElement.play().catch((error) => {\n console.error(\"[HlsAdPlayer] Error starting progressive ad playback:\", error);\n handleAdError();\n });\n } else {\n throw new Error(`Unsupported ad media file type: ${mediaFile.type}`);\n }\n\n return Promise.resolve();\n } catch (error) {\n console.error(\"[HlsAdPlayer] Error playing ad:\", error);\n handleAdError();\n return Promise.reject(error);\n }\n },\n pause() {\n if (!adPlaying || !adVideoElement) {\n return;\n }\n\n try {\n if (adVideoElement && !adVideoElement.paused) {\n adVideoElement.pause();\n }\n } catch (error) {\n console.warn(\"[HlsAdPlayer] Error pausing ad:\", error);\n }\n },\n resume() {\n if (!adPlaying || !adVideoElement) {\n return;\n }\n\n try {\n if (adVideoElement && adVideoElement.paused) {\n adVideoElement.play().catch(() => {});\n }\n } catch (error) {\n console.warn(\"[HlsAdPlayer] Error resuming ad:\", error);\n }\n },\n async stop() {\n console.log(\"[HlsAdPlayer] Stopping ad\");\n adPlaying = false;\n setAdPlayingFlag(false);\n\n const previousMutedState = contentVideo.muted;\n contentVideo.muted = originalMutedState;\n contentVideo.volume = originalMutedState ? 0 : originalVolume;\n console.log(\n `[HlsAdPlayer] Restored mute state on stop: ${previousMutedState} -> ${originalMutedState}`\n );\n\n if (adContainerEl) {\n adContainerEl.style.display = \"none\";\n adContainerEl.style.pointerEvents = \"none\";\n }\n\n contentVideo.style.visibility = \"visible\";\n contentVideo.style.opacity = \"1\";\n\n if (options?.continueLiveStreamDuringAds) {\n if (contentVideo.paused) {\n console.log(\"[HlsAdPlayer] Content video paused in live mode, resuming playback on stop\");\n contentVideo.play().catch(() => {});\n }\n }\n\n if (adHls) {\n adHls.destroy();\n adHls = undefined;\n }\n\n if (adVideoElement) {\n adVideoElement.pause();\n adVideoElement.src = \"\";\n }\n\n currentAd = undefined;\n },\n\n destroy() {\n console.log(\"[HlsAdPlayer] Destroying\");\n destroyed = true;\n \n for (const timeoutId of pendingTimeouts) {\n clearTimeout(timeoutId);\n }\n pendingTimeouts = [];\n \n adPlaying = false;\n setAdPlayingFlag(false);\n contentVideo.muted = originalMutedState;\n contentVideo.volume = originalMutedState ? 0 : originalVolume;\n\n if (adHls) {\n adHls.destroy();\n adHls = undefined;\n }\n\n if (adVideoElement) {\n adVideoElement.pause();\n adVideoElement.src = \"\";\n adVideoElement.remove();\n adVideoElement = undefined;\n }\n\n if (adContainerEl?.parentElement) {\n adContainerEl.parentElement.removeChild(adContainerEl);\n }\n\n adContainerEl = undefined;\n currentAd = undefined;\n listeners.clear();\n preloadedAds.clear();\n preloadingAds.clear();\n },\n\n isAdPlaying() {\n return adPlaying;\n },\n\n resize(width: number, height: number) {\n console.log(`[HlsAdPlayer] Resizing to ${width}x${height}`);\n\n if (adContainerEl) {\n adContainerEl.style.width = `${width}px`;\n adContainerEl.style.height = `${height}px`;\n }\n\n if (adVideoElement) {\n adVideoElement.style.width = `${width}px`;\n adVideoElement.style.height = `${height}px`;\n }\n },\n\n on(event: string, listener: (payload?: any) => void) {\n if (!listeners.has(event)) listeners.set(event, new Set());\n listeners.get(event)!.add(listener);\n },\n\n off(event: string, listener: (payload?: any) => void) {\n listeners.get(event)?.delete(listener);\n },\n\n updateOriginalMutedState(muted: boolean, volume?: number) {\n const nextVolume =\n typeof volume === \"number\" && !Number.isNaN(volume)\n ? Math.max(0, Math.min(1, volume))\n : originalVolume;\n console.log(\n `[HlsAdPlayer] updateOriginalMutedState called: { muted: ${originalMutedState} -> ${muted}, volume: ${originalVolume} -> ${nextVolume} }`\n );\n originalMutedState = muted;\n originalVolume = nextVolume;\n },\n\n getOriginalMutedState() {\n return originalMutedState;\n },\n getOriginalVolume() {\n return originalVolume;\n },\n\n setAdVolume(volume: number) {\n if (adVideoElement && adPlaying) {\n adVideoElement.volume = Math.max(0, Math.min(1, volume));\n }\n },\n\n getAdVolume(): number {\n if (adVideoElement && adPlaying) {\n return adVideoElement.volume;\n }\n return 1;\n },\n showPlaceholder() {\n contentVideo.style.opacity = \"0\";\n contentVideo.style.visibility = \"hidden\";\n \n if (!adContainerEl) {\n const container = document.createElement(\"div\");\n container.style.position = \"absolute\";\n container.style.left = \"0\";\n container.style.top = \"0\";\n container.style.right = \"0\";\n container.style.bottom = \"0\";\n container.style.display = \"none\";\n container.style.alignItems = \"center\";\n container.style.justifyContent = \"center\";\n container.style.pointerEvents = \"none\";\n container.style.zIndex = \"10\";\n container.style.backgroundColor = \"#000\";\n\n contentVideo.parentElement?.appendChild(container);\n adContainerEl = container;\n }\n\n if (adContainerEl) {\n adContainerEl.style.display = \"flex\";\n adContainerEl.style.pointerEvents = \"auto\";\n }\n },\n hidePlaceholder() {\n if (adContainerEl) {\n adContainerEl.style.display = \"none\";\n adContainerEl.style.pointerEvents = \"none\";\n }\n \n if (!adPlaying) {\n contentVideo.style.visibility = \"visible\";\n contentVideo.style.opacity = \"1\";\n }\n },\n };\n}\n","declare global {\n interface Window {\n goog?: any;\n }\n}\n\nconst PAL_SDK_URL =\n \"https://imasdk.googleapis.com/pal/sdkloader/pal.js\";\n\nlet _nonceLoader: any | undefined;\nlet _palLoadPromise: Promise<void> | undefined;\n\nfunction loadPalSdk(): Promise<void> {\n if (typeof window !== \"undefined\" && window.goog?.pal) {\n return Promise.resolve();\n }\n\n if (_palLoadPromise) return _palLoadPromise;\n\n _palLoadPromise = new Promise<void>((resolve, reject) => {\n const existing = document.querySelector(\n 'script[data-pal=\"true\"]'\n ) as HTMLScriptElement | null;\n\n if (existing) {\n if (window.goog?.pal) {\n resolve();\n return;\n }\n const timeout = setTimeout(\n () => reject(new Error(\"PAL SDK load timeout\")),\n 10000\n );\n existing.addEventListener(\"load\", () => {\n clearTimeout(timeout);\n resolve();\n });\n existing.addEventListener(\"error\", () => {\n clearTimeout(timeout);\n reject(new Error(\"PAL SDK load failed\"));\n });\n return;\n }\n\n const script = document.createElement(\"script\");\n script.src = PAL_SDK_URL;\n script.async = true;\n script.setAttribute(\"data-pal\", \"true\");\n script.onload = () => resolve();\n script.onerror = () => reject(new Error(\"PAL SDK load failed\"));\n document.head.appendChild(script);\n });\n\n return _palLoadPromise;\n}\n\nfunction getOrCreateNonceLoader(): any {\n if (_nonceLoader) return _nonceLoader;\n const goog = window.goog;\n const consentSettings = new goog.pal.ConsentSettings();\n consentSettings.allowStorage = true;\n _nonceLoader = new goog.pal.NonceLoader(consentSettings);\n return _nonceLoader;\n}\n\nexport interface PalNonceOptions {\n videoWidth?: number;\n videoHeight?: number;\n descriptionUrl?: string;\n ppid?: string;\n sessionId?: string;\n adWillAutoPlay?: boolean;\n adWillPlayMuted?: boolean;\n continuousPlayback?: boolean;\n}\n\nexport interface PalNonceManager {\n generateNonce(options?: PalNonceOptions): Promise<string>;\n\n getCurrentNonce(): string;\n\n injectNonce(vastTagUrl: string): string;\n\n sendPlaybackStart(): void;\n\n sendPlaybackEnd(): void;\n\n sendAdClick(): void;\n\n sendAdTouch(event: MouseEvent | TouchEvent): void;\n\n reset(): void;\n}\n\nexport function createPalNonceManager(): PalNonceManager {\n let currentNonce = \"\";\n let currentNonceManager: any | undefined;\n\n return {\n async generateNonce(options: PalNonceOptions = {}): Promise<string> {\n try {\n await loadPalSdk();\n\n const loader = getOrCreateNonceLoader();\n const goog = window.goog;\n\n const request = new goog.pal.NonceRequest();\n request.adWillAutoPlay = options.adWillAutoPlay ?? true;\n request.adWillPlayMuted = options.adWillPlayMuted ?? false;\n request.continuousPlayback = options.continuousPlayback ?? true;\n request.descriptionUrl =\n options.descriptionUrl ||\n (typeof window !== \"undefined\" ? window.location.href : \"\");\n request.iconsSupported = true;\n request.playerType = \"StormcloudVideoPlayer\";\n request.playerVersion = \"1.0\";\n request.supportedApiFrameworks = \"2,7,9\";\n request.url =\n options.descriptionUrl ||\n (typeof window !== \"undefined\" ? window.location.href : \"\");\n request.videoWidth = options.videoWidth || 640;\n request.videoHeight = options.videoHeight || 480;\n\n if (options.ppid) request.ppid = options.ppid;\n if (options.sessionId) request.sessionId = options.sessionId;\n\n const manager = await loader.loadNonceManager(request);\n currentNonceManager = manager;\n currentNonce = manager.getNonce() as string;\n\n console.log(\"[PAL] Nonce generated successfully\");\n return currentNonce;\n } catch (error) {\n console.warn(\"[PAL] Failed to generate nonce:\", error);\n currentNonce = \"\";\n currentNonceManager = undefined;\n return \"\";\n }\n },\n\n getCurrentNonce(): string {\n return currentNonce;\n },\n\n injectNonce(vastTagUrl: string): string {\n if (!currentNonce || !vastTagUrl) return vastTagUrl;\n\n try {\n const url = new URL(vastTagUrl);\n url.searchParams.delete(\"paln\");\n url.searchParams.set(\"givn\", currentNonce);\n return url.toString();\n } catch {\n let base = vastTagUrl\n .replace(/([?&])paln=[^&]*/g, \"\")\n .replace(/[?&]$/, \"\");\n const sep = base.includes(\"?\") ? \"&\" : \"?\";\n return `${base}${sep}givn=${encodeURIComponent(currentNonce)}`;\n }\n },\n\n sendPlaybackStart(): void {\n try {\n currentNonceManager?.sendPlaybackStart();\n } catch {}\n },\n\n sendPlaybackEnd(): void {\n try {\n currentNonceManager?.sendPlaybackEnd();\n } catch {}\n },\n\n sendAdClick(): void {\n try {\n currentNonceManager?.sendAdClick();\n } catch {}\n },\n\n sendAdTouch(event: MouseEvent | TouchEvent): void {\n try {\n currentNonceManager?.sendAdTouch(event);\n } catch {}\n },\n\n reset(): void {\n currentNonce = \"\";\n currentNonceManager = undefined;\n },\n };\n}\n","import type {\n ClientInfo,\n TrackingData,\n AdDetectInfo,\n AdLoadedInfo,\n AdImpressionInfo,\n PlayerAnalyticsContext,\n} from \"../types\";\n\nlet cachedBrowserId: string | null = null;\n\nexport function getClientInfo(): ClientInfo {\n const ua = navigator.userAgent;\n const platform = navigator.platform;\n const vendor = navigator.vendor || \"\";\n const maxTouchPoints = navigator.maxTouchPoints || 0;\n const memory = (navigator as any).deviceMemory || null;\n const hardwareConcurrency = navigator.hardwareConcurrency || 1;\n\n const screenInfo = {\n width: screen?.width,\n height: screen?.height,\n availWidth: screen?.availWidth,\n availHeight: screen?.availHeight,\n orientation: (screen?.orientation as any)?.type || \"\",\n pixelDepth: screen?.pixelDepth,\n };\n\n let deviceType: \"tv\" | \"mobile\" | \"tablet\" | \"desktop\" = \"desktop\";\n let brand = \"Unknown\";\n let os = \"Unknown\";\n let model = \"\";\n let isSmartTV = false;\n let isAndroid = false;\n let isWebView = false;\n let isWebApp = false;\n\n if (ua.includes(\"Web0S\")) {\n brand = \"LG\";\n os = \"webOS\";\n isSmartTV = true;\n deviceType = \"tv\";\n const webosMatch = ua.match(/Web0S\\/([^\\s]+)/);\n model = webosMatch ? `webOS ${webosMatch[1]}` : \"webOS TV\";\n } else if (ua.includes(\"Tizen\")) {\n brand = \"Samsung\";\n os = \"Tizen\";\n isSmartTV = true;\n deviceType = \"tv\";\n const tizenMatch = ua.match(/Tizen\\/([^\\s]+)/);\n const tvMatch = ua.match(/(?:Smart-TV|SMART-TV|TV)/i) ? \"Smart TV\" : \"\";\n model = tizenMatch\n ? `Tizen ${tizenMatch[1]} ${tvMatch}`.trim()\n : \"Tizen TV\";\n } else if (ua.includes(\"Philips\")) {\n brand = \"Philips\";\n os = \"Saphi\";\n isSmartTV = true;\n deviceType = \"tv\";\n } else if (ua.includes(\"Sharp\") || ua.includes(\"AQUOS\")) {\n brand = \"Sharp\";\n os = \"Android TV\";\n isSmartTV = true;\n deviceType = \"tv\";\n } else if (\n ua.includes(\"Android\") &&\n (ua.includes(\"Sony\") || vendor.includes(\"Sony\"))\n ) {\n brand = \"Sony\";\n os = \"Android TV\";\n isSmartTV = true;\n deviceType = \"tv\";\n } else if (\n ua.includes(\"Android\") &&\n (ua.includes(\"NetCast\") || ua.includes(\"LG\"))\n ) {\n brand = \"LG\";\n os = \"Android TV\";\n isSmartTV = true;\n deviceType = \"tv\";\n } else if (ua.includes(\" Roku\") || ua.includes(\"Roku/\")) {\n brand = \"Roku\";\n os = \"Roku OS\";\n isSmartTV = true;\n deviceType = \"tv\";\n } else if (ua.includes(\"AppleTV\")) {\n brand = \"Apple\";\n os = \"tvOS\";\n isSmartTV = true;\n deviceType = \"tv\";\n }\n\n if (ua.includes(\"Android\")) {\n isAndroid = true;\n os = \"Android\";\n deviceType = /Mobile/.test(ua) ? \"mobile\" : \"tablet\";\n\n if (\n ua.includes(\"Android\") &&\n (maxTouchPoints === 0 ||\n ua.includes(\"Google TV\") ||\n ua.includes(\"XiaoMi\"))\n ) {\n deviceType = \"tv\";\n isSmartTV = true;\n brand = brand === \"Unknown\" ? \"Android TV\" : brand;\n }\n\n const androidModelMatch = ua.match(/\\(([^)]*Android[^)]*)\\)/);\n if (androidModelMatch && androidModelMatch[1]) {\n model = androidModelMatch[1];\n }\n }\n\n if (/iPad|iPhone|iPod/.test(ua)) {\n os = \"iOS\";\n deviceType = \"mobile\";\n brand = \"Apple\";\n if (navigator.maxTouchPoints > 1 && /iPad/.test(ua)) {\n deviceType = \"tablet\";\n }\n }\n\n if (!isAndroid && !isSmartTV && !/Mobile/.test(ua)) {\n if (ua.includes(\"Windows\")) {\n os = \"Windows\";\n deviceType = \"desktop\";\n } else if (ua.includes(\"Mac\") && !/iPhone/.test(ua)) {\n os = \"macOS\";\n deviceType = \"desktop\";\n if (maxTouchPoints > 1) deviceType = \"tablet\";\n } else if (ua.includes(\"Linux\")) {\n os = \"Linux\";\n deviceType = \"desktop\";\n }\n }\n\n if (brand === \"Unknown\") {\n if (vendor.includes(\"Google\") || ua.includes(\"Chrome\")) brand = \"Google\";\n if (vendor.includes(\"Apple\")) brand = \"Apple\";\n if (vendor.includes(\"Samsung\") || ua.includes(\"SM-\")) brand = \"Samsung\";\n }\n\n isWebView = /wv|WebView|Linux; U;/.test(ua);\n\n if (window?.outerHeight === 0 && window?.outerWidth === 0) {\n isWebView = true;\n }\n\n isWebApp =\n window.matchMedia(\"(display-mode: standalone)\").matches ||\n (window.navigator as any).standalone === true ||\n window.screen?.orientation?.angle !== undefined;\n\n return {\n brand,\n os,\n model: model || ua.substring(0, 50) + \"...\",\n deviceType,\n isSmartTV,\n isAndroid,\n isWebView,\n isWebApp,\n domain: window.location.hostname,\n origin: window.location.origin,\n path: window.location.pathname,\n userAgent: ua,\n vendor,\n platform,\n screen: screenInfo,\n hardwareConcurrency,\n deviceMemory: memory,\n maxTouchPoints,\n language: navigator.language,\n languages: navigator.languages?.join(\",\") || \"\",\n cookieEnabled: navigator.cookieEnabled,\n doNotTrack: navigator.doNotTrack || \"\",\n referrer: document.referrer,\n visibilityState: document.visibilityState,\n };\n}\n\nexport async function getBrowserID(clientInfo: ClientInfo): Promise<string> {\n if (cachedBrowserId) {\n return cachedBrowserId;\n }\n\n const fingerprintString = JSON.stringify(clientInfo);\n\n if (typeof crypto !== \"undefined\" && crypto.subtle && crypto.subtle.digest) {\n try {\n await crypto.subtle.digest(\"SHA-256\", new Uint8Array([1, 2, 3]));\n\n let encodedData: BufferSource;\n if (typeof TextEncoder !== \"undefined\") {\n encodedData = new TextEncoder().encode(fingerprintString);\n } else {\n const utf8 = unescape(encodeURIComponent(fingerprintString));\n const buffer = new Uint8Array(utf8.length);\n for (let i = 0; i < utf8.length; i++) {\n buffer[i] = utf8.charCodeAt(i);\n }\n encodedData = buffer;\n }\n\n const hashBuffer = await crypto.subtle.digest(\"SHA-256\", encodedData);\n const hashArray = Array.from(new Uint8Array(hashBuffer));\n const hashHex = hashArray\n .map((b) => b.toString(16).padStart(2, \"0\"))\n .join(\"\");\n cachedBrowserId = hashHex;\n return hashHex;\n } catch (error) {\n console.warn(\n \"[StormcloudVideoPlayer] crypto.subtle.digest not supported, using fallback hash\"\n );\n }\n }\n\n let hash = 0;\n for (let i = 0; i < fingerprintString.length; i++) {\n const char = fingerprintString.charCodeAt(i);\n hash = (hash << 5) - hash + char;\n hash = hash & hash;\n }\n\n const fallbackHash = Math.abs(hash).toString(16).padStart(8, \"0\");\n const timestamp = Date.now().toString(16).padStart(12, \"0\");\n const random = Math.random().toString(16).substring(2, 14).padStart(12, \"0\");\n\n cachedBrowserId = (fallbackHash + timestamp + random).padEnd(64, \"0\");\n return cachedBrowserId;\n}\n\nconst PLAYER_TRACKING_BASE_URL =\n \"https://adstorm.co/api-adstorm-dev/adstorm/player-tracking\";\nconst TRACK_URL = `${PLAYER_TRACKING_BASE_URL}/metrics/ingest`;\nconst HEARTBEAT_URL = `${PLAYER_TRACKING_BASE_URL}/heartbeat`;\nconst IMPRESSIONS_URL = `${PLAYER_TRACKING_BASE_URL}/impressions/ingest`;\n\ntype PlayerMetricFlags = {\n adLoaded?: boolean;\n adDetect?: boolean;\n captureAt?: string;\n};\n\nfunction buildHeaders(licenseKey: string | undefined): Record<string, string> {\n const headers: Record<string, string> = {\n \"Content-Type\": \"application/json\",\n };\n if (licenseKey) {\n headers[\"Authorization\"] = `Bearer ${licenseKey}`;\n }\n return headers;\n}\n\nasync function sendTrackRequest(\n licenseKey: string | undefined,\n body: Record<string, unknown>\n): Promise<void> {\n const response = await fetch(TRACK_URL, {\n method: \"POST\",\n headers: buildHeaders(licenseKey),\n body: JSON.stringify(body),\n });\n if (!response.ok) {\n throw new Error(`HTTP error! status: ${response.status}`);\n }\n await response.json();\n}\n\nasync function postJson(\n url: string,\n licenseKey: string | undefined,\n body: Record<string, unknown>\n): Promise<void> {\n const response = await fetch(url, {\n method: \"POST\",\n headers: buildHeaders(licenseKey),\n body: JSON.stringify(body),\n });\n if (!response.ok) {\n throw new Error(`HTTP error! status: ${response.status}`);\n }\n await response.json();\n}\n\nasync function buildPlayerMetricEvent(\n licenseKey: string | undefined,\n context: PlayerAnalyticsContext = {},\n flags: PlayerMetricFlags = {}\n): Promise<Record<string, unknown>> {\n const clientInfo = getClientInfo();\n const browserId = await getBrowserID(clientInfo);\n const captureAt = flags.captureAt ?? new Date().toISOString();\n\n return {\n player_id: browserId,\n browserId,\n device_type: clientInfo.deviceType,\n deviceType: clientInfo.deviceType,\n input_stream_type: context.inputStreamType,\n os: clientInfo.os,\n ad_loaded: flags.adLoaded,\n ad_detect: flags.adDetect,\n license_key: licenseKey,\n capture_at: captureAt,\n timestamp: captureAt,\n };\n}\n\nexport async function sendInitialTracking(\n licenseKey?: string,\n context: PlayerAnalyticsContext = {}\n): Promise<void> {\n try {\n const clientInfo = getClientInfo();\n const browserId = await getBrowserID(clientInfo);\n\n const trackingData: TrackingData = {\n browserId,\n ...clientInfo,\n };\n\n await sendTrackRequest(licenseKey, {\n events: [\n {\n player_id: browserId,\n device_type: clientInfo.deviceType,\n input_stream_type: context.inputStreamType,\n os: clientInfo.os,\n ad_loaded: false,\n ad_detect: false,\n license_key: licenseKey,\n capture_at: new Date().toISOString(),\n },\n ],\n trackingData,\n });\n } catch (error) {\n console.error(\n \"[StormcloudVideoPlayer] Error sending initial tracking data:\",\n error\n );\n }\n}\n\nexport async function sendAdDetectTracking(\n licenseKey: string | undefined,\n adDetectInfo: AdDetectInfo,\n context: PlayerAnalyticsContext = {}\n): Promise<void> {\n try {\n await sendHeartbeat(licenseKey, context, {\n adDetect: true,\n captureAt: adDetectInfo.timestamp,\n });\n } catch (error) {\n console.error(\n \"[StormcloudVideoPlayer] Error sending ad detect tracking:\",\n error\n );\n }\n}\n\nexport async function sendAdLoadedTracking(\n licenseKey: string | undefined,\n adLoadedInfo: AdLoadedInfo,\n context: PlayerAnalyticsContext = {}\n): Promise<void> {\n try {\n await sendHeartbeat(licenseKey, context, {\n adLoaded: true,\n captureAt: adLoadedInfo.timestamp,\n });\n } catch (error) {\n console.error(\n \"[StormcloudVideoPlayer] Error sending ad loaded tracking:\",\n error\n );\n }\n}\n\nexport async function sendAdImpressionTracking(\n licenseKey: string | undefined,\n adImpressionInfo: AdImpressionInfo,\n context: PlayerAnalyticsContext = {}\n): Promise<void> {\n try {\n const metricEvent = await buildPlayerMetricEvent(licenseKey, context, {\n captureAt: adImpressionInfo.timestamp,\n });\n await Promise.all([\n postJson(HEARTBEAT_URL, licenseKey, metricEvent),\n postJson(IMPRESSIONS_URL, licenseKey, {\n events: [\n {\n player_id: metricEvent.player_id,\n ad_played_count: 1,\n ad_url: adImpressionInfo.adUrl,\n license_key: licenseKey,\n capture_at: adImpressionInfo.timestamp,\n },\n ],\n }),\n ]);\n } catch (error) {\n console.error(\n \"[StormcloudVideoPlayer] Error sending ad impression tracking:\",\n error\n );\n }\n}\n\nexport async function sendHeartbeat(\n licenseKey?: string,\n context: PlayerAnalyticsContext = {},\n flags: PlayerMetricFlags = {}\n): Promise<void> {\n try {\n const heartbeatData = await buildPlayerMetricEvent(\n licenseKey,\n context,\n flags\n );\n await postJson(HEARTBEAT_URL, licenseKey, heartbeatData);\n } catch (error) {\n console.error(\"[StormcloudVideoPlayer] Error sending heartbeat:\", error);\n }\n}\n","export function polyfillURLSearchParams(): void {\n if (typeof URLSearchParams !== 'undefined') {\n return;\n }\n\n class URLSearchParamsPolyfill {\n private params: Map<string, string[]>;\n\n constructor(init?: string | URLSearchParamsPolyfill) {\n this.params = new Map();\n\n if (typeof init === 'string') {\n this.parseQueryString(init);\n } else if (init instanceof URLSearchParamsPolyfill) {\n init.forEach((value, key) => {\n this.append(key, value);\n });\n }\n }\n\n private parseQueryString(query: string): void {\n const cleanQuery = query.startsWith('?') ? query.slice(1) : query;\n if (!cleanQuery) return;\n\n cleanQuery.split('&').forEach((param) => {\n const [key, value] = param.split('=');\n if (key) {\n const decodedKey = this.safeDecodeURIComponent(key);\n const decodedValue = value ? this.safeDecodeURIComponent(value) : '';\n this.append(decodedKey, decodedValue);\n }\n });\n }\n\n private safeDecodeURIComponent(str: string): string {\n try {\n return decodeURIComponent(str.replace(/\\+/g, ' '));\n } catch (e) {\n return str;\n }\n }\n\n append(name: string, value: string): void {\n const values = this.params.get(name) || [];\n values.push(String(value));\n this.params.set(name, values);\n }\n\n delete(name: string): void {\n this.params.delete(name);\n }\n\n get(name: string): string | null {\n const values = this.params.get(name);\n return values && values.length > 0 && values[0] !== undefined ? values[0] : null;\n }\n\n getAll(name: string): string[] {\n return this.params.get(name) || [];\n }\n\n has(name: string): boolean {\n return this.params.has(name);\n }\n\n set(name: string, value: string): void {\n this.params.set(name, [String(value)]);\n }\n\n forEach(callback: (value: string, key: string, parent: URLSearchParamsPolyfill) => void): void {\n this.params.forEach((values, key) => {\n values.forEach((value) => {\n callback(value, key, this);\n });\n });\n }\n\n toString(): string {\n const parts: string[] = [];\n this.params.forEach((values, key) => {\n values.forEach((value) => {\n parts.push(`${encodeURIComponent(key)}=${encodeURIComponent(value)}`);\n });\n });\n return parts.join('&');\n }\n }\n\n // @ts-ignore\n window.URLSearchParams = URLSearchParamsPolyfill;\n}\n\nexport function polyfillTextEncoder(): void {\n if (typeof TextEncoder !== 'undefined') {\n return;\n }\n\n class TextEncoderPolyfill {\n encoding = 'utf-8';\n\n encode(str: string): Uint8Array {\n const utf8: number[] = [];\n for (let i = 0; i < str.length; i++) {\n let charcode = str.charCodeAt(i);\n if (charcode < 0x80) {\n utf8.push(charcode);\n } else if (charcode < 0x800) {\n utf8.push(0xc0 | (charcode >> 6), 0x80 | (charcode & 0x3f));\n } else if (charcode < 0xd800 || charcode >= 0xe000) {\n utf8.push(\n 0xe0 | (charcode >> 12),\n 0x80 | ((charcode >> 6) & 0x3f),\n 0x80 | (charcode & 0x3f)\n );\n } else {\n i++;\n charcode = 0x10000 + (((charcode & 0x3ff) << 10) | (str.charCodeAt(i) & 0x3ff));\n utf8.push(\n 0xf0 | (charcode >> 18),\n 0x80 | ((charcode >> 12) & 0x3f),\n 0x80 | ((charcode >> 6) & 0x3f),\n 0x80 | (charcode & 0x3f)\n );\n }\n }\n return new Uint8Array(utf8);\n }\n }\n\n // @ts-ignore\n window.TextEncoder = TextEncoderPolyfill;\n}\n\nexport function polyfillPromiseFinally(): void {\n if (typeof Promise !== 'undefined' && !Promise.prototype.finally) {\n Promise.prototype.finally = function (callback: () => void) {\n const constructor = this.constructor as PromiseConstructor;\n return this.then(\n (value) => constructor.resolve(callback()).then(() => value),\n (reason) =>\n constructor.resolve(callback()).then(() => {\n throw reason;\n })\n );\n };\n }\n}\n\nexport function polyfillObjectAssign(): void {\n if (typeof Object.assign !== 'function') {\n Object.assign = function (target: any, ...sources: any[]) {\n if (target == null) {\n throw new TypeError('Cannot convert undefined or null to object');\n }\n\n const to = Object(target);\n\n for (let i = 0; i < sources.length; i++) {\n const nextSource = sources[i];\n\n if (nextSource != null) {\n for (const nextKey in nextSource) {\n if (Object.prototype.hasOwnProperty.call(nextSource, nextKey)) {\n to[nextKey] = nextSource[nextKey];\n }\n }\n }\n }\n\n return to;\n };\n }\n}\n\nexport function polyfillArrayFrom(): void {\n if (!Array.from) {\n Array.from = function (arrayLike: any, mapFn?: any, thisArg?: any) {\n const items = Object(arrayLike);\n if (arrayLike == null) {\n throw new TypeError('Array.from requires an array-like object');\n }\n\n const len = items.length >>> 0;\n const result = new Array(len);\n\n for (let i = 0; i < len; i++) {\n if (mapFn) {\n result[i] = mapFn.call(thisArg, items[i], i);\n } else {\n result[i] = items[i];\n }\n }\n\n return result;\n };\n }\n}\n\nexport function polyfillStringStartsWith(): void {\n if (!String.prototype.startsWith) {\n String.prototype.startsWith = function (search: string, pos?: number) {\n pos = !pos || pos < 0 ? 0 : +pos;\n return this.substring(pos, pos + search.length) === search;\n };\n }\n}\n\nexport function polyfillStringEndsWith(): void {\n if (!String.prototype.endsWith) {\n String.prototype.endsWith = function (search: string, length?: number) {\n if (length === undefined || length > this.length) {\n length = this.length;\n }\n return this.substring(length - search.length, length) === search;\n };\n }\n}\n\nexport function polyfillStringIncludes(): void {\n if (!String.prototype.includes) {\n String.prototype.includes = function (search: string, start?: number) {\n if (typeof start !== 'number') {\n start = 0;\n }\n if (start + search.length > this.length) {\n return false;\n }\n return this.indexOf(search, start) !== -1;\n };\n }\n}\n\nexport function initializePolyfills(): void {\n polyfillObjectAssign();\n polyfillArrayFrom();\n polyfillStringStartsWith();\n polyfillStringEndsWith();\n polyfillStringIncludes();\n polyfillURLSearchParams();\n polyfillTextEncoder();\n polyfillPromiseFinally();\n}\n\n","interface NavigatorUAData {\n platform?: string;\n brands?: Array<{ brand: string; version: string }>;\n mobile?: boolean;\n}\n\ndeclare global {\n interface Navigator {\n userAgentData?: NavigatorUAData;\n }\n}\n\nexport interface BrowserInfo {\n name: string;\n version: string;\n majorVersion: number;\n isSmartTV: boolean;\n isLegacyTV: boolean;\n platform: string;\n supportsModernJS: boolean;\n webOSVersion?: number | undefined;\n tizenVersion?: number | undefined;\n chromeVersion?: number | undefined;\n}\n\nfunction getChromeVersion(ua: string): number {\n const match = ua.match(/Chrome\\/(\\d+)/);\n return match && match[1] ? parseInt(match[1], 10) : 0;\n}\n\nfunction getWebKitVersion(ua: string): number {\n const match = ua.match(/AppleWebKit\\/(\\d+)/);\n return match && match[1] ? parseInt(match[1], 10) : 0;\n}\n\nfunction getPlatform(): string {\n if ('userAgentData' in navigator && navigator.userAgentData?.platform) {\n return navigator.userAgentData.platform;\n }\n\n const ua = navigator.userAgent;\n if (/Mac|iPhone|iPad|iPod/i.test(ua)) {\n return /iPhone|iPad|iPod/i.test(ua) ? 'iPhone' : 'MacIntel';\n }\n if (/Win/i.test(ua)) {\n return 'Win32';\n }\n if (/Linux/i.test(ua)) {\n return /Android/i.test(ua) ? 'Linux armv8l' : 'Linux x86_64';\n }\n if (/CrOS/i.test(ua)) {\n return 'CrOS';\n }\n\n // eslint-disable-next-line deprecation/deprecation\n return (navigator as any).platform || 'Unknown';\n}\n\nexport function detectBrowser(): BrowserInfo {\n const ua = navigator.userAgent;\n const platform = getPlatform();\n\n let name = 'Unknown';\n let version = '0';\n let majorVersion = 0;\n let isSmartTV = false;\n let isLegacyTV = false;\n let supportsModernJS = true;\n let webOSVersion: number | undefined;\n let tizenVersion: number | undefined;\n let chromeVersionNum: number | undefined;\n\n const chromeVersion = getChromeVersion(ua);\n const webkitVersion = getWebKitVersion(ua);\n chromeVersionNum = chromeVersion > 0 ? chromeVersion : undefined;\n\n if (/Web0S|webOS|LG Browser|LGSTB/i.test(ua)) {\n name = 'LG WebOS';\n isSmartTV = true;\n\n let match = ua.match(/Web0S[/\\s]*([\\d.]+)/i) || ua.match(/webOS[/\\s]*([\\d.]+)/i);\n\n if (!match || !match[1]) {\n match = ua.match(/webOSTV[/\\s-]*([\\d.]+)/i) || ua.match(/webOS\\.TV[/\\s-]*([\\d.]+)/i);\n }\n\n if (match && match[1]) {\n version = match[1];\n const parts = version.split('.');\n majorVersion = parts[0] ? parseInt(parts[0], 10) : 0;\n webOSVersion = majorVersion;\n } else if (chromeVersion > 0) {\n if (chromeVersion >= 79) {\n webOSVersion = 6;\n version = '6.0';\n majorVersion = 6;\n } else if (chromeVersion >= 68) {\n webOSVersion = 5;\n version = '5.0';\n majorVersion = 5;\n } else if (chromeVersion >= 53) {\n webOSVersion = 4;\n version = '4.0';\n majorVersion = 4;\n } else if (chromeVersion >= 38) {\n webOSVersion = 3;\n version = '3.0';\n majorVersion = 3;\n } else {\n webOSVersion = 2;\n version = '2.0';\n majorVersion = 2;\n }\n } else {\n version = 'Unknown';\n webOSVersion = undefined;\n }\n\n isLegacyTV = webOSVersion !== undefined && webOSVersion < 3;\n } else if (/Tizen/i.test(ua)) {\n name = 'Samsung Tizen';\n isSmartTV = true;\n const match = ua.match(/Tizen[/\\s]*([\\d.]+)/i);\n version = match && match[1] ? match[1] : 'Unknown';\n if (version !== 'Unknown') {\n const parts = version.split('.');\n majorVersion = parts[0] ? parseInt(parts[0], 10) : 0;\n tizenVersion = majorVersion;\n }\n\n isLegacyTV = tizenVersion !== undefined && tizenVersion < 3;\n } else if (/SMART-TV|SmartTV/i.test(ua)) {\n name = 'Smart TV';\n isSmartTV = true;\n isLegacyTV = chromeVersion > 0 && chromeVersion < 53;\n } else if (/NetCast/i.test(ua)) {\n name = 'LG NetCast';\n isSmartTV = true;\n isLegacyTV = true;\n } else if (/BRAVIA/i.test(ua)) {\n name = 'Sony BRAVIA';\n isSmartTV = true;\n isLegacyTV = chromeVersion > 0 && chromeVersion < 53;\n } else {\n if (chromeVersion > 0) {\n name = 'Chrome';\n version = chromeVersion.toString();\n majorVersion = chromeVersion;\n\n if (chromeVersion < 50) {\n supportsModernJS = false;\n }\n }\n\n if (webkitVersion > 0 && webkitVersion < 600) {\n supportsModernJS = false;\n }\n }\n\n if (typeof Promise === 'undefined' ||\n typeof Map === 'undefined' ||\n typeof Set === 'undefined') {\n supportsModernJS = false;\n }\n\n if (typeof URLSearchParams === 'undefined') {\n supportsModernJS = false;\n }\n\n return {\n name,\n version,\n majorVersion,\n isSmartTV,\n isLegacyTV,\n platform,\n supportsModernJS,\n webOSVersion,\n tizenVersion,\n chromeVersion: chromeVersionNum,\n };\n}\n\nexport function getBrowserConfigOverrides(): {\n allowNativeHls?: boolean;\n} {\n const browser = detectBrowser();\n const overrides: { allowNativeHls?: boolean } = {};\n\n if (browser.isSmartTV) {\n overrides.allowNativeHls = true;\n }\n\n return overrides;\n}\n\nexport function supportsModernJS(): boolean {\n try {\n return (\n typeof Promise !== 'undefined' &&\n typeof Map !== 'undefined' &&\n typeof Set !== 'undefined' &&\n typeof Array.from !== 'undefined' &&\n typeof Object.assign !== 'undefined' &&\n typeof Array.prototype.forEach !== 'undefined' &&\n typeof String.prototype.includes !== 'undefined'\n );\n } catch (e) {\n return false;\n }\n}\n\nexport function logBrowserInfo(debug: boolean = false): void {\n if (!debug) return;\n\n const browser = detectBrowser();\n\n console.log('[StormcloudVideoPlayer] Browser Compatibility Info:', {\n browser: `${browser.name} ${browser.version}`,\n platform: browser.platform,\n isSmartTV: browser.isSmartTV,\n isLegacyTV: browser.isLegacyTV,\n supportsModernJS: browser.supportsModernJS,\n ...(browser.webOSVersion !== undefined ? { webOSVersion: browser.webOSVersion } : {}),\n ...(browser.tizenVersion !== undefined ? { tizenVersion: browser.tizenVersion } : {}),\n ...(browser.chromeVersion !== undefined ? { chromeVersion: browser.chromeVersion } : {}),\n userAgent: navigator.userAgent,\n });\n}\n\nexport function supportsFeature(feature: string): boolean {\n switch (feature) {\n case 'urlsearchparams':\n return typeof URLSearchParams !== 'undefined';\n case 'textencoder':\n return typeof TextEncoder !== 'undefined';\n case 'promises':\n return typeof Promise !== 'undefined';\n case 'fetch':\n return typeof fetch !== 'undefined';\n case 'crypto':\n return typeof crypto !== 'undefined' && typeof crypto.subtle !== 'undefined';\n default:\n return false;\n }\n}\n"]}
|