"use client";

import {
  createContext,
  useContext,
  useEffect,
  useMemo,
  useState,
  ReactNode,
} from "react";

import useStorage from "@/hooks/useStorage";

const STORAGE_KEY = "pfr-client-timezone";
// PFR is UK-based and sessions are scheduled in UK time, so the client view
// defaults to Europe/London (resolved decision) — the viewer can override it
// via the timezone picker, and the choice is persisted in localStorage.
const DEFAULT_TIMEZONE = "Europe/London";

type TimezoneContextValue = {
  timezone: string;
  setTimezone: (tz: string) => void;
};

const TimezoneContext = createContext<TimezoneContextValue | null>(null);

export function TimezoneProvider({ children }: { children: ReactNode }) {
  const [stored, setStored] = useStorage<string>(STORAGE_KEY);
  const [mounted, setMounted] = useState(false);

  // `useStorage` reads localStorage synchronously on the first client render,
  // which would diverge from the server render (DEFAULT_TIMEZONE) and trigger a
  // hydration mismatch. Gate the exposed timezone on `mounted` so the first
  // client render matches the server, then resolve any stored override after
  // mount.
  useEffect(() => {
    setMounted(true);
  }, []);

  const value = useMemo<TimezoneContextValue>(
    () => ({
      timezone: mounted ? (stored ?? DEFAULT_TIMEZONE) : DEFAULT_TIMEZONE,
      setTimezone: setStored,
    }),
    [mounted, stored, setStored],
  );

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

export function useTimezone() {
  const ctx = useContext(TimezoneContext);
  if (!ctx) {
    throw new Error("useTimezone must be used within a TimezoneProvider");
  }
  return ctx;
}
