stormcloud-video-player 0.7.50 → 0.8.0
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/FilePlayer.cjs.map +1 -1
- 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/polyfills.cjs.map +1 -1
- 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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AAAA,IAA0D;QAC9DC,IAAM;QACNC,eAAiB;QACjBC,gBAAkB;QAClBC,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","call","key","__toESM","mod","isNodeMode","__esModule","value","__toCommonJS","StormcloudVideoPlayer_exports","StormcloudVideoPlayerComponent","module","exports","import_react","require","import_hls","createHlsAdPlayer","contentVideo","options","adPlaying","originalMutedState","listeners","Map","licenseKey","mainHlsInstance","adVideoElement","adHls","adContainerEl","currentAd","sessionId","preloadedAds","preloadingAds","destroyed","pendingTimeouts","impression","start","firstQuartile","midpoint","thirdQuartile","complete","emit","event","payload","set","Array","fn","error","console","warn","fireTrackingPixels","generateSessionId","Math","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","exitFullscreen","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","skip","el","eventKey","clickThrough","id","response","vastXml","fetch","vastTagUrl","mode","credentials","headers","referrerPolicy","ok","statusText","text","substring","createAdVideoElement","video","document","createElement","style","position","left","top","objectFit","backgroundColor","muted","volume","setupAdEventListeners","addEventListener","progress","trackingFired","handleAdComplete","e","handleAdError","currentTime","setAdPlayingFlag","isPlaying","dataset","stormcloudAdPlaying","display","pointerEvents","initialize","container","right","bottom","alignItems","justifyContent","zIndex","parentElement","appendChild","has","ad","Promise","reject","resolve","play","contentVolume","adVolume","isHlsAd","originalVolume","max","min","continueLiveStreamDuringAds","Hls","isSupported","destroy","enableWorker","lowLatencyMode","loadSource","attachMedia","on","Events","MANIFEST_PARSED","catch","ERROR","data","fatal","canPlayType","src","load","paused","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","getOrCreateNonceLoader","consentSettings","ConsentSettings","allowStorage","NonceLoader","createPalNonceManager","currentNonce","currentNonceManager","generateNonce","loader","request","manager","loadPalSdk","NonceRequest","adWillAutoPlay","adWillPlayMuted","continuousPlayback","descriptionUrl","location","href","iconsSupported","playerType","playerVersion","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","doNotTrack","referrer","visibilityState","fingerprintString","getBrowserID","clientInfo","encodedData","utf8","buffer","i","hashBuffer","hashArray","hashHex","hash","char","fallbackHash","timestamp","JSON","stringify","crypto","subtle","digest","TextEncoder","encode","unescape","Uint8Array","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","device_type","input_stream_type","inputStreamType","ad_loaded","adLoaded","ad_detect","adDetect","capture_at","trackingData","events","toISOString","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","assign","sources","TypeError","nextSource","nextKey","polyfillArrayFrom","arrayLike","mapFn","thisArg","items","len","result","polyfillStringStartsWith","search","pos","polyfillStringEndsWith","polyfillStringIncludes","initializePolyfills","polyfillObjectAssign","getChromeVersion","getWebKitVersion","getPlatform","userAgentData","detectBrowser","version","majorVersion","isLegacyTV","supportsModernJS","webOSVersion","tizenVersion","chromeVersionNum","chromeVersion","webkitVersion","browser","overrides","allowNativeHls","logBrowserInfo","debug","adPodQueue","StormcloudVideoPlayer","config","attached","ptsDriftEmaMs","vmapBreaks","consumedVmapBreakIds","Set","lastHeartbeatTime","currentAdIndex","totalAdsInBreak","isLiveStream","nativeHlsMode","videoSrcProtection","bufferedSegmentsCount","shouldAutoplayAfterBuffering","hasInitialBufferCompleted","adRequestTokenCounter","activeAdRequestToken","adRequestWatchdogToken","adFailsafeToken","failedVastUrls","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","inAdBreak","_evt","fragments","fragmentsToScan","frag","tagList","isArray","entry","tag","idx","indexOf","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","attachImaEventListeners","source","adIndex","remaining","getRemainingAdMs","queuedUrls","tryNextAvailableAdWithRateLimit","handleAdPodComplete","errorPayload","errorMessage","errorCode","code","vastErrorCode","message","cause","innerError","causeMessage","handleAdFailure","clearAdRequestWatchdog","showAds","resetGamNoFillCounter","expectedAdBreakDurationMs","adStopTimerId","scheduleAdStopCountdown","currentMuted","currentVolume","clearAdFailsafeTimer","recreateAdController","shouldShowPlaceholder","showPlaceholderLayer","showPlaceholder","preservedMutedState","preservedVolumeState","ensurePlaceholderContainer","transition","placeholderContainer","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","daterangeId","toIdentityString","ID","candidates","candidate","isFinite","cue","createScte35Cue","pendingKey","getPendingScte35CueKey","startAdPrefetch","shouldAcceptScte35EndCue","activeScte35BreakKey","hasRecentlyHandledScte35Cue","markScte35CueHandled","onScte35Marker","getScte35CueKey","getScte35MarkerRaw","spliceEventId","splice_event_id","segmentationEventId","segmentation_event_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","nowMs","driftToleranceMs","deltaMs","estCurrentPtsMs","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","tableId","totalLength","addScte35SectionMarker","subarray","assemblers","bytes","expectedLength","appendScte35Bytes","assembler","section","hasProcessedTsScte35Section","buf","BitReader","checksum","pointerField","bitPos","readBits","numBits","remainingInByte","toRead","currentByte","bytePos","shift","mask","bits","skipBits","bytePosition","readSpliceTime","timeSpecifiedFlag","r","ptsAdjustmentTicks","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"],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;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\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/newpallibrary.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/newpallibrary.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"]}
|