"use client";

import { useEffect, useRef } from "react";
import { useAudioSync } from "@/hooks/useAudioSync";
import { useAppSelector } from "@/store/hooks";
import { viewService } from "@/services/viewService";
import { startActivityTracking } from "@/lib/activityTracker";

// Always mounted in layout.tsx — keeps audio sync alive on every page,
// including /now-playing where BottomPlayer is hidden.
export default function PlayerController() {
  useAudioSync();

  const currentTrack = useAppSelector((s) => s.player.currentTrack);
  const firedTrackRef = useRef<string | null>(null);

  /* Start global inactivity tracker once (singleton — safe to call multiple times) */
  useEffect(() => {
    const cleanup = startActivityTracking();
    return cleanup;
  }, []);

  /* Fire add_view once per track when music starts playing */
  useEffect(() => {
    if (!currentTrack) return;
    const key = `${currentTrack.contentType}-${currentTrack.id}`;
    if (firedTrackRef.current === key) return;
    firedTrackRef.current = key;
    viewService.addView(currentTrack.contentType, currentTrack.id).catch(() => {});
  }, [currentTrack]);

  return null;
}
