import { createContext, useContext, useState, useEffect, useRef, ReactNode } from "react";
import { sendPageLog } from "../../services/userLogService";

interface PageTrackingContextValue {
  currentPage: string | null;
  setCurrentPage: (pageTitle: string | null) => void;
}

const PageTrackingContext = createContext<PageTrackingContextValue | null>(null);

interface PageTrackingProviderProps {
  children: ReactNode;
}

export function PageTrackingProvider({ children }: PageTrackingProviderProps) {
  const [currentPage, setCurrentPage] = useState<string | null>(null);
  const intervalRef = useRef<NodeJS.Timeout | null>(null);
  const isMountedRef = useRef(true);

  useEffect(() => {
    isMountedRef.current = true;

    // Start global 10-second interval
    intervalRef.current = setInterval(() => {
      // Only send log if page is visible and mounted
      if (isMountedRef.current && currentPage && !document.hidden) {
        sendPageLog(currentPage);
      }
    }, 10000); // 10 seconds

    return () => {
      isMountedRef.current = false;
      if (intervalRef.current) {
        clearInterval(intervalRef.current);
      }
    };
  }, [currentPage]);

  return (
    <PageTrackingContext.Provider value={{ currentPage, setCurrentPage }}>
      {children}
    </PageTrackingContext.Provider>
  );
}

export function usePageTrackingContext(): PageTrackingContextValue {
  const context = useContext(PageTrackingContext);
  if (!context) {
    throw new Error("usePageTrackingContext must be used within PageTrackingProvider");
  }
  return context;
}
