/**
 * TimezoneProvider.
 *
 * Fetches the IANA timezone configured during the BanGUI setup wizard and
 * makes it available throughout the component tree via React Context.
 *
 * The timezone is fetched once at mount.  On error or before the initial
 * fetch resolves, the value defaults to ``"UTC"`` so date-formatting callers
 * always receive a safe fallback.
 */

import { createContext, useMemo } from "react";
import { useTimezoneData } from "../hooks/useTimezoneData";

// ---------------------------------------------------------------------------
// Context definition
// ---------------------------------------------------------------------------

export interface TimezoneContextValue {
  /** IANA timezone string, e.g. ``"Europe/Berlin"`` or ``"UTC"``. */
  timezone: string;
}

export const TimezoneContext = createContext<TimezoneContextValue | undefined>(undefined);

// ---------------------------------------------------------------------------
// Provider
// ---------------------------------------------------------------------------

export interface TimezoneProviderProps {
  children: React.ReactNode;
}

/**
 * Wrap the application (or authenticated shell) with this provider to make the
 * configured timezone available via {@link useTimezone}.
 *
 * @example
 * ```tsx
 * <TimezoneProvider>
 *   <App />
 * </TimezoneProvider>
 * ```
 */
export function TimezoneProvider({
  children,
}: TimezoneProviderProps): React.JSX.Element {
  const { timezone } = useTimezoneData();

  const value = useMemo<TimezoneContextValue>(() => ({ timezone }), [timezone]);

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