'use client';

import { createContext, useCallback, useContext, useMemo, useRef } from 'react';

interface RemasterPlayCountContextType {
  /**
   * Marks a clip as played in this modal session and returns whether
   * this is the first time it's being played in this session.
   */
  markClipPlayedAndCheckIfFirst: (clipId: string) => boolean;

  /**
   * Resets the tracking for a new modal session
   */
  resetSession: () => void;
}

const RemasterPlayCountContext =
  createContext<RemasterPlayCountContextType | null>(null);

export function RemasterPlayCountProvider({
  children,
}: {
  children: React.ReactNode;
}) {
  // Track which clips have been played in this modal session
  const playedClipsRef = useRef<Set<string>>(new Set());

  const markClipPlayedAndCheckIfFirst = useCallback(
    (clipId: string): boolean => {
      const isFirstPlay = !playedClipsRef.current.has(clipId);
      if (isFirstPlay) {
        playedClipsRef.current.add(clipId);
      }
      return isFirstPlay;
    },
    []
  );

  const resetSession = useCallback(() => {
    playedClipsRef.current.clear();
  }, []);

  const value = useMemo(
    () => ({
      markClipPlayedAndCheckIfFirst,
      resetSession,
    }),
    [markClipPlayedAndCheckIfFirst, resetSession]
  );

  return (
    <RemasterPlayCountContext.Provider value={value}>
      {children}
    </RemasterPlayCountContext.Provider>
  );
}

export function useRemasterPlayCount() {
  const context = useContext(RemasterPlayCountContext);
  return context;
}
