/**
 * TrackView - Macro component for declarative page/section view tracking.
 *
 * Usage (macro pattern — wrap any component to auto-track views):
 *   <TrackView name="product_detail" properties={{ '{{' }} productId {{ '}}' }}>
 *     <ProductDetail />
 *   </TrackView>
 *
 *   <TrackView name="dashboard" trackOnMount>
 *     <Dashboard />
 *   </TrackView>
 *
 * ⚠️ AUTO-GENERATED BY PRISM — DO NOT EDIT
 */

import React, { useEffect, useRef } from 'react';
import { useAnalytics } from '../hooks/useAnalytics';

interface TrackViewProps {
  /** Event name for the view tracking */
  name: string;
  /** Optional properties to include with the event */
  properties?: Record<string, unknown>;
  /** Track on mount (default: true) */
  trackOnMount?: boolean;
  /** Track when component becomes visible via IntersectionObserver */
  trackOnVisible?: boolean;
  /** Children to render */
  children: React.ReactNode;
}

/**
 * Macro component that tracks when a section is viewed.
 *
 * Use this as a declarative wrapper to track views without
 * adding imperative tracking code to your components.
 */
export function TrackView({
  name,
  properties,
  trackOnMount = true,
  trackOnVisible = false,
  children,
}: TrackViewProps) {
  const { trackEvent } = useAnalytics();
  const elementRef = useRef<HTMLDivElement>(null);
  const trackedRef = useRef(false);

  // Track on mount
  useEffect(() => {
    if (trackOnMount && !trackOnVisible && !trackedRef.current) {
      trackedRef.current = true;
      trackEvent(`view_${name}`, {
        ...properties,
        page_url: window.location.pathname,
      });
    }
  }, [name, trackOnMount, trackOnVisible, trackEvent, properties]);

  // Track on visibility (IntersectionObserver)
  useEffect(() => {
    if (!trackOnVisible || !elementRef.current) return;

    const observer = new IntersectionObserver(
      (entries) => {
        entries.forEach((entry) => {
          if (entry.isIntersecting && !trackedRef.current) {
            trackedRef.current = true;
            trackEvent(`view_${name}`, {
              ...properties,
              page_url: window.location.pathname,
              visible: true,
            });
          }
        });
      },
      { threshold: 0.5 }
    );

    observer.observe(elementRef.current);
    return () => observer.disconnect();
  }, [name, trackOnVisible, trackEvent, properties]);

  if (trackOnVisible) {
    return <div ref={elementRef}>{children}</div>;
  }

  return <>{children}</>;
}
