'use client';

import { useParams, usePathname } from 'next/navigation';
import { useEffect, useRef } from 'react';
import storageAvailable from 'storage-available';

import { useStores } from '@/app/(root)/AppProviders';
import { setLSShareData } from '@/components/ga4/utils';
import {
  SHAREABLE_CONTENT_TYPE_PATH_PREFIXES,
  getContentTypeFromPath,
} from '@/utils/share';

const LAST_INTERACTION_KEY = 'sh-last-interaction';
const LAST_INTERACTION_EXPIRY_MS = 1000 * 60 * 60 * 24; // 1 day

/**
 * A hook that saves in localStorage the first visited shared content
 * so we can attribute a user signup to the first shared content they interact with
 */
export default function useSharedContentTracker() {
  const pathname = usePathname();
  const params = useParams();

  // don't want changes to these to trigger re-renders
  const stateRef = useRef<{
    isInitialized: boolean;
  }>({
    isInitialized: false,
  });

  useEffect(() => {
    // we should only run this once in a given tab session
    // this will also run if the user copy/pastes a song link
    // to the current tab, or opens a new tab and navigates to a song
    // also, if the user interacted with suno at some point, we should
    // not overwrite with a new share
    const firstVisitToSunoOnThisTab = !stateRef.current.isInitialized;
    const lastInteraction = localStorage.getItem(LAST_INTERACTION_KEY);
    const isShareTrackedPage = SHAREABLE_CONTENT_TYPE_PATH_PREFIXES.some(
      (prefix: string) => pathname.startsWith(prefix)
    );
    const userHasntInteractedInAWhile =
      !lastInteraction ||
      Date.now() - parseInt(lastInteraction) > LAST_INTERACTION_EXPIRY_MS;

    if (
      isShareTrackedPage &&
      firstVisitToSunoOnThisTab &&
      userHasntInteractedInAWhile
    ) {
      // If all these conditions are met, we assume the user was
      // shared a song link (without share params)
      const contentType = getContentTypeFromPath(pathname);
      const contentId = params.slug as string;
      setLSShareData(null, contentType, contentId);
    }

    stateRef.current.isInitialized = true;
  }, []);

  // if users interacted with suno at all, we store that in localStorage
  // so we don't overwrite with a new share
  const { playbar: playbarStore } = useStores();
  useEffect(() => {
    // When user interacts with Suno (changes page, plays a clip, etc.)
    // we update localStorage to mark that they've had an interaction
    if (storageAvailable('localStorage')) {
      localStorage.setItem(LAST_INTERACTION_KEY, Date.now().toString());
    }
  }, [pathname, playbarStore.isPlaying, playbarStore.clip]);
}
