"use client";

import { fetchOnce } from "@/lib/fetch-once";

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

/** The module switches from System settings → Modules. */
export type ModuleKey =
  | "reels" | "stories" | "communities" | "marketplace" | "events"
  | "crowdfunding" | "news" | "leaderboard" | "wallet"
  | "gifts" | "ads" | "contact" | "support"
  | "jobs" | "offers";

/** Each module, the setting behind it, and the paths it owns. */
export const MODULE_PATHS: Record<ModuleKey, { setting: string; paths: string[] }> = {
  reels: { setting: "reelsEnabled", paths: ["/reels"] },
  stories: { setting: "storiesEnabled", paths: ["/stories"] },
  communities: { setting: "communitiesEnabled", paths: ["/communities", "/groups", "/pages"] },
  marketplace: { setting: "marketplaceEnabled", paths: ["/marketplace"] },
  events: { setting: "eventsEnabled", paths: ["/events"] },
  crowdfunding: { setting: "crowdfundingEnabled", paths: ["/crowdfunding"] },
  news: { setting: "newsEnabled", paths: ["/news"] },
  leaderboard: { setting: "leaderboardEnabled", paths: ["/leaderboard"] },
  wallet: { setting: "walletEnabled", paths: ["/wallet"] },
  jobs: { setting: "jobsEnabled", paths: ["/jobs"] },
  offers: { setting: "offersEnabled", paths: ["/offers"] },
  gifts: { setting: "giftsEnabled", paths: [] },
  ads: { setting: "adsEnabled", paths: ["/ads"] },
  contact: { setting: "contactEnabled", paths: ["/contact"] },
  support: { setting: "supportEnabled", paths: ["/support"] },
};

const Ctx = createContext<Record<string, boolean>>({});

/** Makes the module switches available to every page. */
export function ModulesProvider({ children }: { children: React.ReactNode }) {
  const [modules, setModules] = useState<Record<string, boolean>>({});

  useEffect(() => {
    fetchOnce<{ modules?: Record<string, boolean> }>("/api/settings")
      .then((d) => d)
      .then((d) => d?.modules && setModules(d.modules))
      .catch(() => {});
  }, []);

  return <Ctx.Provider value={modules}>{children}</Ctx.Provider>;
}

/**
 * Whether a module is on. Defaults to true so nothing disappears while the
 * settings are still loading.
 */
/** All the module switches at once. */
export function useModules(): Record<string, boolean> {
  return useContext(Ctx);
}

export function useModule(key: ModuleKey): boolean {
  const modules = useContext(Ctx);
  return modules[key] !== false;
}

/** Whether a path belongs to a module that's switched off. */
export function useIsPathBlocked(pathname: string): boolean {
  const modules = useContext(Ctx);

  return Object.entries(MODULE_PATHS).some(([key, { paths }]) => {
    if (modules[key] !== false) return false;
    return paths.some((p) => pathname === p || pathname.startsWith(p + "/"));
  });
}
