/**
 * useFunnelEvents - React hook for registration funnel tracking
 *
 * Provides type-safe methods for tracking user journey events:
 * - Visit tracking (optional auto-track)
 * - Registration with attribution context
 * - Profile completion, content creation, purchases
 *
 * @example
 * ```tsx
 * const { trackRegistration, captureEntryReferrer } = useFunnelEvents({
 *   userId: user?.id,
 *   audience: 'client',
 * });
 *
 * useEffect(() => {
 *   captureEntryReferrer();
 * }, []);
 *
 * const handleSubmit = () => {
 *   trackRegistration({ registrationType: 'focused' });
 * };
 * ```
 */

import { useCallback, useEffect } from 'react';
import { useLocation } from '@lilith/ui-router';

import {
  getSessionId,
  captureEntryReferrer,
  getAndClearEntryReferrer,
  emitFunnelEvent,
} from './funnel-events';
import type {
  FunnelEvent,
  FunnelEventPayload,
  SignupContext,
  UseFunnelEventsConfig,
} from './types';

export { captureEntryReferrer };

/**
 * Hook for tracking registration funnel events.
 *
 * @param config - Configuration for the hook
 * @param config.userId - Current user ID (if authenticated)
 * @param config.audience - User audience type (worker/client)
 * @param config.userType - User type string
 * @param config.autoTrackVisits - Whether to auto-track page visits (default: false)
 */
export function useFunnelEvents(config: UseFunnelEventsConfig = {}) {
  const { userId, audience, userType, autoTrackVisits = false } = config;
  const location = useLocation();

  const basePayload = useCallback(
    (): Omit<FunnelEventPayload, 'event'> => ({
      route: location.pathname,
      sessionId: getSessionId(),
      timestamp: new Date().toISOString(),
      userId,
      audience,
      userType,
    }),
    [location.pathname, userId, audience, userType]
  );

  // Auto-track visits when enabled
  useEffect(() => {
    if (autoTrackVisits) {
      emitFunnelEvent({
        ...basePayload(),
        event: 'visit',
        referrer: document.referrer || undefined,
      });
    }
  }, [autoTrackVisits, basePayload]);

  /**
   * Manually track a page visit event
   */
  const trackVisit = useCallback(() => {
    emitFunnelEvent({
      ...basePayload(),
      event: 'visit',
      referrer: document.referrer || undefined,
    });
  }, [basePayload]);

  /**
   * Track a registration event with optional context
   *
   * @param context - Registration context (path, type, audience override)
   */
  const trackRegistration = useCallback(
    (context?: SignupContext) => {
      emitFunnelEvent({
        ...basePayload(),
        event: 'registration',
        audience: context?.audience ?? audience,
        userType: context?.userType ?? userType,
        registrationPath: context?.registrationPath ?? location.pathname,
        registrationType: context?.registrationType,
        entryReferrer: getAndClearEntryReferrer(),
      });
    },
    [basePayload, audience, userType, location.pathname]
  );

  /**
   * Track a generic funnel event (profile_complete, first_content, etc.)
   */
  const trackEvent = useCallback(
    (event: Exclude<FunnelEvent, 'visit' | 'registration'>) => {
      emitFunnelEvent({ ...basePayload(), event });
    },
    [basePayload]
  );

  return {
    trackVisit,
    trackRegistration,
    trackProfileComplete: () => trackEvent('profile_complete'),
    trackFirstContent: () => trackEvent('first_content'),
    trackSubscribe: () => trackEvent('subscribe'),
    trackPurchase: () => trackEvent('purchase'),
    trackRepeatPurchase: () => trackEvent('repeat_purchase'),
    captureEntryReferrer,
  };
}
