import { createContext, useContext, type ReactNode } from "react";
import type { IAnalytics } from "../analytics.interface";

const AnalyticsContext = createContext<IAnalytics | null>(null);

export class AnalyticsContextError extends Error {
  constructor() {
    super("useAnalytics() must be called within an <AnalyticsProvider>.");
    this.name = "AnalyticsContextError";
  }
}

export function AnalyticsProvider({
  value,
  children,
}: {
  value: IAnalytics;
  children: ReactNode;
}) {
  return (
    <AnalyticsContext.Provider value={value}>
      {children}
    </AnalyticsContext.Provider>
  );
}

export function useAnalytics(): IAnalytics {
  const analytics = useContext(AnalyticsContext);
  if (analytics === null) {
    throw new AnalyticsContextError();
  }
  return analytics;
}
