/**
 * `useMapData` hook — fetches and manages ban-by-country data with debouncing.
 *
 * This hook wraps {@link useBansByCountry} and adds a 300ms debounce to reduce
 * unnecessary fetches when filters change rapidly (e.g., during user interaction
 * with UI controls).
 */

import { useCallback, useEffect, useRef } from "react";
import { useBansByCountry } from "./useBansByCountry";
import type { BanOriginFilter, TimeRange } from "../types/ban";
import type { MapBanItem } from "../types/map";

// ---------------------------------------------------------------------------
// Constants
// ---------------------------------------------------------------------------

/** Debounce delay in milliseconds before firing a fetch after filter changes. */
const DEBOUNCE_MS = 300;

// ---------------------------------------------------------------------------
// Return type
// ---------------------------------------------------------------------------

export interface UseMapDataResult {
  /** Per-country ban counts (ISO alpha-2 → count). */
  countries: Record<string, number>;
  /** ISO alpha-2 → country name mapping. */
  countryNames: Record<string, string>;
  /** All ban records in the selected window. */
  bans: MapBanItem[];
  /** Total ban count. */
  total: number;
  /** True while a fetch is in flight. */
  loading: boolean;
  /** Error message or null. */
  error: string | null;
  /** Trigger a manual re-fetch. */
  refresh: () => void;
}

// ---------------------------------------------------------------------------
// Hook
// ---------------------------------------------------------------------------

export function useMapData(
  range: TimeRange = "24h",
  origin: BanOriginFilter = "all",
  source: "fail2ban" | "archive" = "fail2ban",
  countryCode?: string,
): UseMapDataResult {
  const debounceRef = useRef<ReturnType<typeof setTimeout> | null>(null);

  const base = useBansByCountry(range, origin, source, countryCode, false);

  const load = useCallback((): void => {
    // Cancel any pending debounce timer.
    if (debounceRef.current != null) {
      clearTimeout(debounceRef.current);
    }

    debounceRef.current = setTimeout((): void => {
      base.refresh();
    }, DEBOUNCE_MS);
    // base.refresh is memoized with all relevant deps; including base would cause
    // unnecessary recreations on every render due to object identity.
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [base.refresh]);

  useEffect((): (() => void) => {
    load();
    return (): void => {
      if (debounceRef.current != null) {
        clearTimeout(debounceRef.current);
      }
    };
  }, [load]);

  return {
    countries: base.countries,
    countryNames: base.countryNames,
    bans: base.bans,
    total: base.total,
    loading: base.loading,
    error: base.error,
    refresh: load,
  };
}

