'use client';

import { useEffect } from 'react';

const sendToClarity = (pageName: string, timeSpentSeconds: number) => {
  if (typeof window !== 'undefined' && (window as any).clarity) {
    (window as any).clarity('event', `page_timing_${pageName}`, {
      time_spent_seconds: timeSpentSeconds,
      page: pageName,
      timestamp: new Date().toISOString(),
    });
  }
};

export const usePageTiming = (pageName: string) => {
  useEffect(() => {
    const startTime = Date.now();

    const handleBeforeUnload = () => {
      const timeSpent = Math.round((Date.now() - startTime) / 1000);
      sendToClarity(pageName, timeSpent);
    };

    window.addEventListener('beforeunload', handleBeforeUnload);

    return () => {
      window.removeEventListener('beforeunload', handleBeforeUnload);
      const timeSpent = Math.round((Date.now() - startTime) / 1000);
      sendToClarity(pageName, timeSpent);
    };
  }, [pageName]);
};
