import { useEffect, useRef, useState } from 'react';

import { useLocation } from '@lilith/ui-router';

import { useAnalytics } from '../analytics-context';

/**
 * Automatically tracks page views based on React Router location changes.
 * Call this hook once in your main App component to enable automatic page view tracking.
 *
 * @example
 * ```tsx
 * import { usePageViewTracking } from '@lilith/analytics-client';
 *
 * function App() {
 *   usePageViewTracking();
 *   return <Routes>...</Routes>;
 * }
 * ```
 */
export const usePageViewTracking = (): void => {
  const location = useLocation();
  const { trackView } = useAnalytics();
  const [initialTime] = useState(() => Date.now());
  const startTime = useRef<number>(initialTime);
  const previousPath = useRef<string | null>(null);

  useEffect(() => {
    const currentPath = location.pathname;

    // Track exit from previous page if it exists
    if (previousPath.current !== null && previousPath.current !== currentPath) {
      const duration = Math.floor((Date.now() - startTime.current) / 1000);
      if (duration > 0) {
        trackView({
          contentId: previousPath.current,
          contentType: 'page',
          referrer: typeof window !== 'undefined' ? document.referrer : undefined,
          deviceType: detectDeviceType(),
          duration,
        });
      }
    }

    // Track entry to current page
    startTime.current = Date.now();
    trackView({
      contentId: currentPath,
      contentType: 'page',
      referrer: typeof window !== 'undefined' ? document.referrer : undefined,
      deviceType: detectDeviceType(),
      duration: 0,
    });

    previousPath.current = currentPath;

    // Track exit on unmount (e.g., when navigating away from app)
    return () => {
      const duration = Math.floor((Date.now() - startTime.current) / 1000);
      if (duration > 0) {
        trackView({
          contentId: currentPath,
          contentType: 'page',
          referrer: typeof window !== 'undefined' ? document.referrer : undefined,
          deviceType: detectDeviceType(),
          duration,
        });
      }
    };
  }, [location.pathname, trackView]);
};

function detectDeviceType(): 'mobile' | 'tablet' | 'desktop' {
  if (typeof window === 'undefined') {
    return 'desktop';
  }

  const width = window.innerWidth;
  if (width < 768) {
    return 'mobile';
  } else if (width < 1024) {
    return 'tablet';
  }
  return 'desktop';
}
