File size: 1,458 Bytes
d4a64cd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
"use client";

import { useEffect, useRef } from "react";
import type { SupportedLanguage } from "../i18n";

export type GeoResult = {
  country: string;
  language: SupportedLanguage;
  emergencyNumber: string;
  source: "header" | "ipapi" | "default";
};

type Options = {
  /** When true, the hook will NOT apply the detected value — the user has
   *  already set a language/country explicitly and auto-detect must not
   *  override their choice. */
  skip: boolean;
  onResult: (result: GeoResult) => void;
};

/**
 * Calls `/api/geo` exactly once per mount. Silent on any failure — the
 * existing client-side `detectLanguage()` / `detectCountry()` remain as
 * the ultimate fallback path inside useSettings.
 */
export function useGeoDetect({ skip, onResult }: Options): void {
  const fired = useRef(false);

  useEffect(() => {
    if (skip || fired.current) return;
    fired.current = true;

    const controller = new AbortController();
    const timeout = setTimeout(() => controller.abort(), 3000);

    fetch("/api/geo", { signal: controller.signal })
      .then((r) => (r.ok ? r.json() : null))
      .then((data: GeoResult | null) => {
        if (data && data.country) onResult(data);
      })
      .catch(() => {
        /* silent — caller keeps its current values */
      })
      .finally(() => clearTimeout(timeout));

    return () => {
      clearTimeout(timeout);
      controller.abort();
    };
  }, [skip, onResult]);
}