'use client';

import { useEffect } from 'react';
import { useAnalytics } from './useAnalytics';
import { AnalyticsEvents } from './analytics-events';

interface BlogEngagementTrackerProps {
  title: string;
  slug: string;
  category?: string;
  readingTime: number;
}

/**
 * BlogEngagementTracker
 * Tracks reading time and article completion.
 */
export default function BlogEngagementTracker({
  title,
  slug,
  category,
  readingTime,
}: BlogEngagementTrackerProps) {
  const { trackEvent } = useAnalytics();

  useEffect(() => {
    // Article start
    trackEvent(AnalyticsEvents.BLOG_POST_VIEW, {
      title,
      slug,
      category,
      estimated_reading_time: readingTime,
      location: 'blog_post_pdp',
    });

    const startTime = Date.now();

    return () => {
      const dwellTime = Math.round((Date.now() - startTime) / 1000);

      // We only consider it a "read" if they stay a reasonable amount of time
      // or if they scroll (covered by ScrollDepthTracker)
      trackEvent('blog_dwell_time', {
        title,
        slug,
        seconds: dwellTime,
        reading_time_completion: Math.min(100, Math.round((dwellTime / (readingTime * 60)) * 100)),
      });
    };
  }, [title, slug, category, readingTime, trackEvent]);

  return null;
}
