"use client";

import { createContext, useContext, ReactNode, useMemo } from "react";
import type { AnalyticsService } from "@mintel/observability";
import {
  NoopAnalyticsService,
  UmamiAnalyticsService,
} from "@mintel/observability";

const AnalyticsContext = createContext<AnalyticsService>(
  new NoopAnalyticsService(),
);

export interface AnalyticsContextProviderProps {
  service?: AnalyticsService;
  config?: {
    enabled: boolean;
    websiteId?: string;
    apiEndpoint: string;
  };
  children: ReactNode;
}

export function AnalyticsContextProvider({
  service,
  config,
  children,
}: AnalyticsContextProviderProps) {
  const activeService = useMemo(() => {
    if (service) return service;
    if (config) return new UmamiAnalyticsService(config);
    return new NoopAnalyticsService();
  }, [service, config]);

  return (
    <AnalyticsContext.Provider value={activeService}>
      {children}
    </AnalyticsContext.Provider>
  );
}

export function useAnalytics() {
  const context = useContext(AnalyticsContext);
  if (!context) {
    throw new Error(
      "useAnalytics must be used within an AnalyticsContextProvider",
    );
  }
  return context;
}
