/**
 * TikTok Pixel helper (browser-side).
 *
 * Each call generates a unique event_id and returns it so the caller
 * can forward it to the server for dual reporting / deduplication.
 */

interface TtqObject {
  track: (eventName: string, params?: Record<string, unknown>) => void;
  page: () => void;
  identify: (params: Record<string, unknown>) => void;
}

const getTtq = (): TtqObject | undefined => {
  if (typeof window === 'undefined') return undefined;
  const ttq = (window as unknown as { ttq?: TtqObject }).ttq;
  return ttq && typeof ttq.track === 'function' ? ttq : undefined;
};

const generateEventId = (): string =>
  `${Date.now()}-${Math.random().toString(36).slice(2, 11)}`;

export const triggerTtqEvent = (
  eventName: string,
  params?: Record<string, unknown>,
): string => {
  const eventId = generateEventId();
  const ttq = getTtq();
  if (!ttq) return eventId;
  try {
    const fullParams = { ...params, event_id: eventId };
    ttq.track(eventName, fullParams);
  } catch (error) {
    console.error('TikTok pixel tracking failed', error);
  }
  return eventId;
};
