import { createContext, useCallback, useContext, useMemo, useState, type ReactNode } from "react";
import type { DataSource } from "../domain/types";
import { createRepos } from "./createRepos";
import type { Repos } from "./repos";

type DataContextValue = {
  repos: Repos;
  /** 固定 live（mock 資料源已移除） */
  dataSource: DataSource;
  refresh: () => void;
  tick: number;
};

const DataContext = createContext<DataContextValue | null>(null);

export function DataProvider({ children }: { children: ReactNode }) {
  const [tick, setTick] = useState(0);
  const refresh = useCallback(() => setTick((t) => t + 1), []);
  const repos = useMemo(() => createRepos(), []);

  const value = useMemo(
    () => ({ repos, dataSource: "live" as const, refresh, tick }),
    [repos, refresh, tick],
  );

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

export function useData(): DataContextValue {
  const ctx = useContext(DataContext);
  if (!ctx) throw new Error("useData must be used within DataProvider");
  return ctx;
}

export function useRepos(): Repos {
  return useData().repos;
}
