'use client';

import React from 'react';
import { AnalyticsBrowser } from '@segment/analytics-next';

const segment = isEnabled()
  ? AnalyticsBrowser.load({ writeKey: '6wlLwaKVTEU8dwOr7jKfBJoeM9pMBSLu' })
  : null;

function isEnabled() {
  return process.env.NODE_ENV === 'production';
}

async function track(event: string, properties: Record<string, unknown> = {}) {
  if (!segment || !isEnabled()) return;

  segment.track(`${event} - [Dev Studio]`, properties);
}

export async function getAnonymousId(): Promise<string | null> {
  if (!segment || !isEnabled()) return null;

  const user = await segment.user();
  const anonymouseId = user.anonymousId();

  return anonymouseId as string;
}

async function setAnonymousId(id: string) {
  if (!segment || !isEnabled()) return null;

  await segment.setAnonymousId(id);
}

export const SegmentContext = React.createContext<{
  track: (event: string, properties?: Record<string, unknown>) => void;
  getAnonymousId: () => Promise<string | null>;
  setAnonymousId: (id: string) => Promise<void | null>;
}>({ track, getAnonymousId, setAnonymousId });

export function useSegment() {
  return React.useContext(SegmentContext);
}

export function SegmentProvider({ children }) {
  return (
    <SegmentContext.Provider value={{ track, getAnonymousId, setAnonymousId }}>
      {children}
    </SegmentContext.Provider>
  );
}
