"use client";

import { createContext, useContext, useEffect, useMemo, useRef, useState } from "react";
import { useTopLoader } from "nextjs-toploader";

type ApiLoadingContextValue = {
  isLoading: boolean;
};

const ApiLoadingContext = createContext<ApiLoadingContextValue>({ isLoading: false });

/** In-flight request cache: same method+url+body shares one network request; each caller gets a cloned response. */
const inFlightMap = new Map<string, Promise<Response>>();

function getRequestKey(input: RequestInfo | URL, init?: RequestInit): string {
  const url = typeof input === "string" ? input : input instanceof Request ? input.url : input.toString();
  const method = (typeof input === "object" && input instanceof Request ? input.method : init?.method) ?? "GET";
  const body = (typeof input === "object" && input instanceof Request ? input.body : init?.body) ?? undefined;
  const bodyKey = body == null ? "" : typeof body === "string" ? body : `_${Date.now()}_${Math.random()}`;
  return `${method}|${url}|${bodyKey}`;
}

export function ApiLoadingProvider({ children }: { children: React.ReactNode }) {
  const [requestCount, setRequestCount] = useState(0);
  const loader = useTopLoader();
  const loaderActive = useRef(false);

  useEffect(() => {
    if (typeof window === "undefined") return;

    const globalWindow = window as Window & {
      __oxyfinz_fetch_wrapped__?: boolean;
      __oxyfinz_original_fetch__?: typeof window.fetch;
    };

    if (globalWindow.__oxyfinz_fetch_wrapped__) {
      return;
    }

    globalWindow.__oxyfinz_original_fetch__ =
      globalWindow.__oxyfinz_original_fetch__ ?? globalWindow.fetch;
    const baseFetch = globalWindow.__oxyfinz_original_fetch__;

    let mounted = true;

    const wrappedFetch: typeof window.fetch = async (input, init) => {
      if (!mounted) {
        return baseFetch(input, init);
      }

      const key = getRequestKey(input, init);
      const existing = inFlightMap.get(key);

      if (existing) {
        return existing.then((res) => res.clone());
      }

      const promise = baseFetch(input, init).then(
        (res) => {
          inFlightMap.delete(key);
          return res;
        },
        (err) => {
          inFlightMap.delete(key);
          throw err;
        }
      );
      inFlightMap.set(key, promise);

      // Increment synchronously — mounted is guaranteed true here (checked above,
      // and JS is single-threaded so nothing can unmount between that check and here).
      setTimeout(() => {
  if (mounted) setRequestCount((prev) => prev + 1);
    }, 0);
    try {
      const response = await promise;
      return response.clone();
    } finally {
      setTimeout(() => {
        if (mounted) setRequestCount((prev) => Math.max(prev - 1, 0));
      }, 0);
    }
    };

    globalWindow.fetch = wrappedFetch as typeof window.fetch;
    globalWindow.__oxyfinz_fetch_wrapped__ = true;

    return () => {
      mounted = false;
      globalWindow.fetch = baseFetch;
      globalWindow.__oxyfinz_fetch_wrapped__ = false;
    };
  }, []);

  /**
   * Drive the top progress bar from the in-flight request count.
   *
   * This used to render a full-screen `<GlobalLoader />` scrim whenever any
   * fetch was outstanding, which meant the entire app greyed out and became
   * unclickable during background refreshes — including ones the user never
   * asked for. The bar communicates the same thing without seizing the page,
   * so content stays readable and interactive while data loads.
   */
  useEffect(() => {
    const busy = requestCount > 0;

    if (busy && !loaderActive.current) {
      loaderActive.current = true;
      loader.start();
    } else if (!busy && loaderActive.current) {
      loaderActive.current = false;
      loader.done();
    }
  }, [requestCount, loader]);

  // Never strand the bar at partial width if the provider unmounts mid-flight.
  useEffect(
    () => () => {
      if (loaderActive.current) loader.done(true);
    },
    [loader]
  );

  const value = useMemo(
    () => ({
      isLoading: requestCount > 0,
    }),
    [requestCount]
  );

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

export const useApiLoading = () => useContext(ApiLoadingContext);
