'use strict';

var chunkWGEGR3DF_cjs = require('./chunk-WGEGR3DF.cjs');
var zustand = require('zustand');
var middleware = require('zustand/middleware');
var shallow = require('zustand/react/shallow');
var lib = require('@djangocfg/ui-core/lib');

var cacheDebug = lib.createLogger("MediaCache");
var STREAM_URL_TTL = 30 * 1e3;
var DEFAULT_VIDEO_SETTINGS = {
  volume: 1,
  isLooping: false
};
var initialState = {
  blobUrls: /* @__PURE__ */ new Map(),
  imageDimensions: /* @__PURE__ */ new Map(),
  audioPlaybackPositions: /* @__PURE__ */ new Map(),
  audioEffectConfigs: /* @__PURE__ */ new Map(),
  videoStreamUrls: /* @__PURE__ */ new Map(),
  videoPosterUrls: /* @__PURE__ */ new Map(),
  videoPlaybackPositions: /* @__PURE__ */ new Map(),
  videoMetadata: /* @__PURE__ */ new Map(),
  videoPlayerSettings: DEFAULT_VIDEO_SETTINGS
};
var useMediaCacheStore = zustand.create()(
  middleware.devtools(
    middleware.persist(
      (set, get) => ({
        ...initialState,
        // ========== Blob URL Management ==========
        getOrCreateBlobUrl: /* @__PURE__ */ chunkWGEGR3DF_cjs.__name((key, content, mimeType) => {
          const existing = get().blobUrls.get(key);
          if (existing) {
            cacheDebug.debug(`Blob URL reused: ${key}`, { refCount: existing.refCount + 1 });
            set(
              (state) => ({
                blobUrls: new Map(state.blobUrls).set(key, {
                  ...existing,
                  refCount: existing.refCount + 1
                })
              }),
              false,
              "blobUrl/incrementRef"
            );
            return existing.url;
          }
          const blob = new Blob([content], { type: mimeType });
          const url = URL.createObjectURL(blob);
          const sizeMB = (content.byteLength / 1024 / 1024).toFixed(2);
          cacheDebug.debug(`Blob URL created: ${key}`, { mimeType, size: `${sizeMB}MB` });
          set(
            (state) => ({
              blobUrls: new Map(state.blobUrls).set(key, {
                url,
                refCount: 1,
                createdAt: Date.now()
              })
            }),
            false,
            "blobUrl/create"
          );
          return url;
        }, "getOrCreateBlobUrl"),
        releaseBlobUrl: /* @__PURE__ */ chunkWGEGR3DF_cjs.__name((key) => {
          const entry = get().blobUrls.get(key);
          if (!entry) return;
          if (entry.refCount <= 1) {
            cacheDebug.debug(`Blob URL revoked: ${key}`);
            URL.revokeObjectURL(entry.url);
            set(
              (state) => {
                const newMap = new Map(state.blobUrls);
                newMap.delete(key);
                return { blobUrls: newMap };
              },
              false,
              "blobUrl/revoke"
            );
          } else {
            cacheDebug.debug(`Blob URL released: ${key}`, { refCount: entry.refCount - 1 });
            set(
              (state) => ({
                blobUrls: new Map(state.blobUrls).set(key, {
                  ...entry,
                  refCount: entry.refCount - 1
                })
              }),
              false,
              "blobUrl/decrementRef"
            );
          }
        }, "releaseBlobUrl"),
        hasBlobUrl: /* @__PURE__ */ chunkWGEGR3DF_cjs.__name((key) => get().blobUrls.has(key), "hasBlobUrl"),
        // ========== Image Cache ==========
        cacheDimensions: /* @__PURE__ */ chunkWGEGR3DF_cjs.__name((src, dims) => {
          set(
            (state) => ({
              imageDimensions: new Map(state.imageDimensions).set(src, dims)
            }),
            false,
            "image/cacheDimensions"
          );
        }, "cacheDimensions"),
        getDimensions: /* @__PURE__ */ chunkWGEGR3DF_cjs.__name((src) => get().imageDimensions.get(src) ?? null, "getDimensions"),
        // ========== Audio Cache ==========
        saveAudioPosition: /* @__PURE__ */ chunkWGEGR3DF_cjs.__name((uri, time) => {
          set(
            (state) => ({
              audioPlaybackPositions: new Map(state.audioPlaybackPositions).set(
                uri,
                time
              )
            }),
            false,
            "audio/savePosition"
          );
        }, "saveAudioPosition"),
        getAudioPosition: /* @__PURE__ */ chunkWGEGR3DF_cjs.__name((uri) => get().audioPlaybackPositions.get(uri) ?? null, "getAudioPosition"),
        getEffectConfig: /* @__PURE__ */ chunkWGEGR3DF_cjs.__name((key) => get().audioEffectConfigs.get(key) ?? null, "getEffectConfig"),
        cacheEffectConfig: /* @__PURE__ */ chunkWGEGR3DF_cjs.__name((key, config) => {
          set(
            (state) => ({
              audioEffectConfigs: new Map(state.audioEffectConfigs).set(
                key,
                config
              )
            }),
            false,
            "audio/cacheEffectConfig"
          );
        }, "cacheEffectConfig"),
        // ========== Video Cache ==========
        getOrCreateStreamUrl: /* @__PURE__ */ chunkWGEGR3DF_cjs.__name((sessionId, path, generator) => {
          const key = `${sessionId}:${path}`;
          const cached = get().videoStreamUrls.get(key);
          if (cached && Date.now() - cached.timestamp < STREAM_URL_TTL) {
            return cached.url;
          }
          const url = generator(sessionId, path);
          set(
            (state) => ({
              videoStreamUrls: new Map(state.videoStreamUrls).set(key, {
                url,
                timestamp: Date.now()
              })
            }),
            false,
            "video/cacheStreamUrl"
          );
          return url;
        }, "getOrCreateStreamUrl"),
        getPosterUrl: /* @__PURE__ */ chunkWGEGR3DF_cjs.__name((title) => get().videoPosterUrls.get(title) ?? null, "getPosterUrl"),
        cachePosterUrl: /* @__PURE__ */ chunkWGEGR3DF_cjs.__name((title, url) => {
          set(
            (state) => ({
              videoPosterUrls: new Map(state.videoPosterUrls).set(title, url)
            }),
            false,
            "video/cachePosterUrl"
          );
        }, "cachePosterUrl"),
        saveVideoPosition: /* @__PURE__ */ chunkWGEGR3DF_cjs.__name((key, time) => {
          set(
            (state) => ({
              videoPlaybackPositions: new Map(state.videoPlaybackPositions).set(
                key,
                time
              )
            }),
            false,
            "video/savePosition"
          );
        }, "saveVideoPosition"),
        getVideoPosition: /* @__PURE__ */ chunkWGEGR3DF_cjs.__name((key) => get().videoPlaybackPositions.get(key) ?? null, "getVideoPosition"),
        cacheVideoMetadata: /* @__PURE__ */ chunkWGEGR3DF_cjs.__name((url, meta) => {
          set(
            (state) => ({
              videoMetadata: new Map(state.videoMetadata).set(url, meta)
            }),
            false,
            "video/cacheMetadata"
          );
        }, "cacheVideoMetadata"),
        getVideoMetadata: /* @__PURE__ */ chunkWGEGR3DF_cjs.__name((url) => get().videoMetadata.get(url) ?? null, "getVideoMetadata"),
        invalidateSession: /* @__PURE__ */ chunkWGEGR3DF_cjs.__name((sessionId) => {
          set(
            (state) => {
              const newUrls = new Map(state.videoStreamUrls);
              for (const [key] of newUrls) {
                if (key.startsWith(`${sessionId}:`)) {
                  newUrls.delete(key);
                }
              }
              return { videoStreamUrls: newUrls };
            },
            false,
            "video/invalidateSession"
          );
        }, "invalidateSession"),
        getVideoPlayerSettings: /* @__PURE__ */ chunkWGEGR3DF_cjs.__name(() => get().videoPlayerSettings, "getVideoPlayerSettings"),
        saveVideoPlayerSettings: /* @__PURE__ */ chunkWGEGR3DF_cjs.__name((settings) => {
          set(
            (state) => ({
              videoPlayerSettings: { ...state.videoPlayerSettings, ...settings }
            }),
            false,
            "video/savePlayerSettings"
          );
        }, "saveVideoPlayerSettings"),
        // ========== Global ==========
        clearCache: /* @__PURE__ */ chunkWGEGR3DF_cjs.__name(() => {
          const stats = get().getCacheStats();
          cacheDebug.info("Clearing cache", stats);
          get().blobUrls.forEach(({ url }) => URL.revokeObjectURL(url));
          set(initialState, false, "clearCache");
        }, "clearCache"),
        getCacheStats: /* @__PURE__ */ chunkWGEGR3DF_cjs.__name(() => ({
          blobUrls: get().blobUrls.size,
          dimensions: get().imageDimensions.size,
          audioPositions: get().audioPlaybackPositions.size,
          videoPositions: get().videoPlaybackPositions.size
        }), "getCacheStats")
      }),
      {
        name: "media-cache-storage",
        // Only persist playback positions, poster URLs, and player settings
        partialize: /* @__PURE__ */ chunkWGEGR3DF_cjs.__name((state) => ({
          audioPlaybackPositions: Array.from(
            state.audioPlaybackPositions.entries()
          ),
          videoPlaybackPositions: Array.from(
            state.videoPlaybackPositions.entries()
          ),
          videoPosterUrls: Array.from(state.videoPosterUrls.entries()),
          videoPlayerSettings: state.videoPlayerSettings
        }), "partialize"),
        // Rehydrate Maps from arrays
        onRehydrateStorage: /* @__PURE__ */ chunkWGEGR3DF_cjs.__name(() => (state) => {
          if (state) {
            const persistedAudio = state.audioPlaybackPositions;
            const persistedVideo = state.videoPlaybackPositions;
            const persistedPosters = state.videoPosterUrls;
            const persistedSettings = state.videoPlayerSettings;
            state.audioPlaybackPositions = new Map(
              Array.isArray(persistedAudio) ? persistedAudio : []
            );
            state.videoPlaybackPositions = new Map(
              Array.isArray(persistedVideo) ? persistedVideo : []
            );
            state.videoPosterUrls = new Map(
              Array.isArray(persistedPosters) ? persistedPosters : []
            );
            state.videoPlayerSettings = {
              ...DEFAULT_VIDEO_SETTINGS,
              ...persistedSettings && typeof persistedSettings === "object" ? persistedSettings : {}
            };
          }
        }, "onRehydrateStorage")
      }
    ),
    { name: "MediaCacheStore" }
  )
);
var useImageCache = /* @__PURE__ */ chunkWGEGR3DF_cjs.__name(() => useMediaCacheStore(
  shallow.useShallow((state) => ({
    getOrCreateBlobUrl: state.getOrCreateBlobUrl,
    releaseBlobUrl: state.releaseBlobUrl,
    hasBlobUrl: state.hasBlobUrl,
    cacheDimensions: state.cacheDimensions,
    getDimensions: state.getDimensions
  }))
), "useImageCache");
var useAudioCache = /* @__PURE__ */ chunkWGEGR3DF_cjs.__name(() => useMediaCacheStore(
  shallow.useShallow((state) => ({
    getOrCreateBlobUrl: state.getOrCreateBlobUrl,
    releaseBlobUrl: state.releaseBlobUrl,
    hasBlobUrl: state.hasBlobUrl,
    saveAudioPosition: state.saveAudioPosition,
    getAudioPosition: state.getAudioPosition,
    getEffectConfig: state.getEffectConfig,
    cacheEffectConfig: state.cacheEffectConfig
  }))
), "useAudioCache");
var useVideoCache = /* @__PURE__ */ chunkWGEGR3DF_cjs.__name(() => useMediaCacheStore(
  shallow.useShallow((state) => ({
    getOrCreateBlobUrl: state.getOrCreateBlobUrl,
    releaseBlobUrl: state.releaseBlobUrl,
    hasBlobUrl: state.hasBlobUrl,
    getOrCreateStreamUrl: state.getOrCreateStreamUrl,
    getPosterUrl: state.getPosterUrl,
    cachePosterUrl: state.cachePosterUrl,
    saveVideoPosition: state.saveVideoPosition,
    getVideoPosition: state.getVideoPosition,
    cacheVideoMetadata: state.cacheVideoMetadata,
    getVideoMetadata: state.getVideoMetadata,
    invalidateSession: state.invalidateSession,
    getVideoPlayerSettings: state.getVideoPlayerSettings,
    saveVideoPlayerSettings: state.saveVideoPlayerSettings
  }))
), "useVideoCache");
var useVideoPlayerSettings = /* @__PURE__ */ chunkWGEGR3DF_cjs.__name(() => useMediaCacheStore(
  shallow.useShallow((state) => ({
    settings: state.videoPlayerSettings,
    saveSettings: state.saveVideoPlayerSettings
  }))
), "useVideoPlayerSettings");
function useBlobUrlCleanup(key) {
  const releaseBlobUrl = useMediaCacheStore((s) => s.releaseBlobUrl);
  if (typeof window !== "undefined") {
    const { useEffect } = chunkWGEGR3DF_cjs.__require("react");
    useEffect(() => {
      return () => {
        if (key) {
          releaseBlobUrl(key);
        }
      };
    }, [key, releaseBlobUrl]);
  }
}
chunkWGEGR3DF_cjs.__name(useBlobUrlCleanup, "useBlobUrlCleanup");
function generateContentKey(content) {
  const arr = new Uint8Array(content);
  const len = arr.length;
  const start = arr.slice(0, Math.min(1024, len));
  const end = arr.slice(Math.max(0, len - 1024));
  let hash = len;
  for (let i = 0; i < start.length; i++) {
    hash = (hash << 5) - hash + start[i] | 0;
  }
  for (let i = 0; i < end.length; i++) {
    hash = (hash << 5) - hash + end[i] | 0;
  }
  return `blob-${len}-${hash.toString(16)}`;
}
chunkWGEGR3DF_cjs.__name(generateContentKey, "generateContentKey");

exports.generateContentKey = generateContentKey;
exports.useAudioCache = useAudioCache;
exports.useBlobUrlCleanup = useBlobUrlCleanup;
exports.useImageCache = useImageCache;
exports.useMediaCacheStore = useMediaCacheStore;
exports.useVideoCache = useVideoCache;
exports.useVideoPlayerSettings = useVideoPlayerSettings;
//# sourceMappingURL=chunk-77HQWEQ6.cjs.map
//# sourceMappingURL=chunk-77HQWEQ6.cjs.map