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

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

interface UseTrackPageViewOptions {
  pageName?: string;
  userId?: string;
  enabled?: boolean;
}

export const useTrackPageView = (options: UseTrackPageViewOptions = {}): void => {
  const { trackView } = useAnalytics();
  const [initialTime] = useState(() => Date.now());
  const startTime = useRef<number>(initialTime);

  const pageName = options.pageName ?? (typeof window !== 'undefined' ? window.location.pathname : '/');

  useEffect(() => {
    if (options.enabled === false) {
      return;
    }

    const referrer = typeof window !== 'undefined' ? document.referrer : undefined;
    const deviceType = detectDeviceType();
    const effectStartTime = startTime.current;

    trackView({
      contentId: pageName,
      contentType: 'post',
      userId: options.userId,
      referrer,
      deviceType,
      duration: 0,
    });

    return () => {
      const duration = Math.floor((Date.now() - effectStartTime) / 1000);
      if (duration > 0) {
        trackView({
          contentId: pageName,
          contentType: 'post',
          userId: options.userId,
          referrer,
          deviceType,
          duration,
        });
      }
    };
  }, [pageName, options.userId, options.enabled, 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';
}
