import React, { createContext, useContext, useMemo, type ReactNode } from 'react';

import { createMixpanelClient, type MixpanelClient } from './mixpanelClient';

// Web builder's project token, so native events stitch with web.
const MIXPANEL_PROJECT_TOKEN = 'eff913a25a5a2642acc7794bb28dc621';

// No-op fallback so useAgentBi() outside a provider never crashes on analytics.
const NOOP_CLIENT: MixpanelClient = {
  track: async () => {},
  trackEditor: async () => {},
  trackHome: async () => {},
  identify: () => {},
  register: () => {},
};

const MixpanelContext = createContext<MixpanelClient | null>(null);

interface MixpanelProviderProps {
  distinctId?: string | null;
  environment?: string;
  superProperties?: Record<string, unknown>;
  children: ReactNode;
}

export function MixpanelProvider({
  distinctId,
  environment,
  superProperties,
  children,
}: MixpanelProviderProps) {
  // Created once: the UI only mounts post-login, so distinctId is stable. user_id
  // and app_id are seeded as super-properties to mirror the web builder's session
  // context; app_id starts null (home list) and is updated via register().
  const client = useMemo(
    () =>
      createMixpanelClient({
        token: MIXPANEL_PROJECT_TOKEN,
        distinctId,
        environment,
        superProperties: { user_id: distinctId ?? null, app_id: null, ...superProperties },
      }),
    // eslint-disable-next-line react-hooks/exhaustive-deps
    [],
  );

  return <MixpanelContext.Provider value={client}>{children}</MixpanelContext.Provider>;
}

export function useAgentBi(): MixpanelClient {
  return useContext(MixpanelContext) ?? NOOP_CLIENT;
}
