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

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

import type { ViewEventData } from '../types';

interface UseTrackViewOptions {
  contentId: string;
  contentType: ViewEventData['contentType'];
  userId?: string;
  deviceType?: ViewEventData['deviceType'];
  enabled?: boolean;
}

export const useTrackView = (options: UseTrackViewOptions): void => {
  const { trackView } = useAnalytics();
  const [initialTime] = useState(() => Date.now());
  const startTime = useRef<number>(initialTime);
  const hasTracked = useRef<boolean>(false);

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

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

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

    hasTracked.current = true;

    return () => {
      const duration = Math.floor((Date.now() - effectStartTime) / 1000);
      if (duration > 0) {
        trackView({
          contentId: options.contentId,
          contentType: options.contentType,
          userId: options.userId,
          referrer,
          deviceType,
          duration,
        });
      }
    };
  }, [options, trackView]);
};

function detectDeviceType(): ViewEventData['deviceType'] {
  if (typeof window === 'undefined') {
    return 'desktop';
  }

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