const LOCAL_PLAYER_STORAGE_BASE = window.SongfilmApiConfig.getBase("storage");
const LOCAL_PLAYER_RENDERER_BASE = window.SongfilmApiConfig.getBase("remotion");

function LocalAlbumsPlayerView({ albums, initialAlbumId = null, initialSongId = null, onExit }) {
  const audioUrlCacheRef = React.useRef(new Map());

  const hasAudioAsset = (song) => (
    !!(song?.audioServerUrl || song?.audio?.filename || song?.audio?.url || song?.exportState?.audioFilename || song?.audioStorageKey)
  );
  const hasVideoAsset = (song) => !!(song?.exportState?.videoFilename || song?.exportState?.jobId);

  const resolveAudioUrl = React.useCallback(async (song) => {
    const cacheKey = song?.id || song?.filename || song?.title || "";
    const cached = audioUrlCacheRef.current.get(cacheKey);
    if (cached) return cached;

    const serverRef = String(song?.audioServerUrl || song?.audio?.filename || song?.audio?.url || song?.exportState?.audioFilename || "").trim();
    if (serverRef) {
      const built = window.SongfilmApiConfig?.buildMediaUrl
        ? window.SongfilmApiConfig.buildMediaUrl("audio", serverRef)
        : `${LOCAL_PLAYER_STORAGE_BASE}/audio/${encodeURIComponent(serverRef)}`;
      audioUrlCacheRef.current.set(cacheKey, built);
      return built;
    }

    const restored = await window.SongfilmSongStorage?.restoreAudioUrl?.(song);
    if (restored) audioUrlCacheRef.current.set(cacheKey, restored);
    return restored || "";
  }, []);

  const resolveVideoUrl = React.useCallback((song) => {
    const videoFilename = String(song?.exportState?.videoFilename || "").trim();
    if (videoFilename) {
      return window.SongfilmApiConfig?.buildMediaUrl
        ? window.SongfilmApiConfig.buildMediaUrl("video", videoFilename)
        : `${LOCAL_PLAYER_STORAGE_BASE}/video/${encodeURIComponent(videoFilename)}`;
    }

    const jobId = String(song?.exportState?.jobId || "").trim();
    if (jobId) return `${LOCAL_PLAYER_RENDERER_BASE}/render/${jobId}/file`;
    return "";
  }, []);

  return (
    <AlbumPlayerView
      albums={albums}
      initialAlbumId={initialAlbumId}
      initialSongId={initialSongId}
      onExit={onExit}
      copy={{
        headerLabel: "MY WORKSPACE",
        title: "앨범 플레이어",
        subtitle: "나의 모든 앨범을 목록에서 펼쳐 오디오/비디오로 재생합니다.",
        loadingText: "",
        emptyText: "등록된 앨범이 없습니다.",
      }}
      hasAudioAsset={hasAudioAsset}
      hasVideoAsset={hasVideoAsset}
      resolveAudioUrl={resolveAudioUrl}
      resolveVideoUrl={resolveVideoUrl}
      getAlbumItems={(items) => items}
      getAlbumFromItem={(album) => album || null}
      getItemId={(album) => album?.id || ""}
      getCardTitle={(item, album) => album?.title || "Untitled Album"}
      getCardSubtitle={(item, album) => `${album?.artist || "Unknown"} · ${album?.songs?.length || 0}곡`}
      getCardBadge={(item, album) => album?.year || "LOCAL"}
      getPanelLabel={() => "내 워크스페이스 플레이어"}
      getPanelPublisher={(item, album) => album?.artist || "Unknown Artist"}
      getSelectedMissingText={() => "선택한 앨범 데이터를 찾지 못했습니다."}
    />
  );
}

Object.assign(window, { LocalAlbumsPlayerView });
