'use client';

import { ReactNode, useEffect } from 'react';
import { usePageTiming } from '../hooks/usePageTiming';
import { triggerTtqEvent } from '../../lib/tiktok';

interface OnboardingPageWrapperProps {
  pageName: string;
  children: ReactNode;
}

export function OnboardingPageWrapper({ pageName, children }: OnboardingPageWrapperProps) {
  usePageTiming(pageName);

  useEffect(() => {
    const viewEventId = triggerTtqEvent('ViewContent', {
      content_id: pageName,
      content_name: pageName,
    });

    const ttEvents: Array<{
      eventName: string;
      eventId: string;
      contentId?: string;
      contentName?: string;
    }> = [
      {
        eventName: 'ViewContent',
        eventId: viewEventId,
        contentId: pageName,
        contentName: pageName,
      },
    ];

    if (pageName === 'plansone') {
      const regEventId = triggerTtqEvent('CompleteRegistration');
      ttEvents.push({ eventName: 'CompleteRegistration', eventId: regEventId });
    }

    fetch('/api/track', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ page: pageName, ttEvents }),
    }).catch(() => {});
  }, [pageName]);

  return <>{children}</>;
}
