import { useCallback, useEffect, useMemo, useRef, useState, type ReactNode } from 'react' import { useLocation, useNavigate } from 'react-router' import regionPages from '../../seo/region.json' import { nearestRegion } from '@nalssigak/shared/api/client/sdk.gen' import type { RegionData } from '@nalssigak/shared/api/client/types.gen' import { track } from '../lib/analytics' import { IS_TOSS, tossLocation } from '../lib/platform' import { DEFAULT_REGION, ownPage, pageOf, RegionContext, type LocateStatus } from './regionContext' const KEY = 'nalssigak.b.region' type RegionPage = (typeof regionPages)[number] /** 지역 페이지 안의 구: 구로 나뉜 시는 r 이 그 시 안이면 r, 아니면 시청이 있는 구 */ function regionIn(page: RegionPage, r?: RegionData | null): RegionData { return page.regions.find((g) => g.code === r?.code) ?? page.regions.find((g) => g.code === page.main)! } function readStored(): RegionData | null { try { const raw = localStorage.getItem(KEY) return raw ? (JSON.parse(raw) as RegionData) : null } catch { // 사파리 프라이빗 모드 등에서는 저장소를 못 쓴다 → 기본 구로 시작 return null } } function writeStored(r: RegionData) { try { localStorage.setItem(KEY, JSON.stringify(r)) } catch { // 저장이 막혀도 이번 방문 동안은 메모리 값으로 계속 쓴다 return } } export function RegionProvider({ children }: { children: ReactNode }) { const { pathname } = useLocation() const navigate = useNavigate() const page = pageOf(pathname) const pageRef = useRef(page) const dayRef = useRef(pathname.startsWith('/tomorrow/') ? 'tomorrow' : 'today') useEffect(() => { pageRef.current = page dayRef.current = pathname.startsWith('/tomorrow/') ? 'tomorrow' : 'today' }, [page, pathname]) const [stored] = useState(readStored) const [landing] = useState(page) const [chosen, setRegionState] = useState(() => (page ? regionIn(page, stored) : (stored ?? DEFAULT_REGION))) // 앱 안에서 다른 지역 페이지로 옮겨 가면 그 지역으로 const region = page && !page.regions.some((g) => g.code === chosen.code) ? regionIn(page, stored) : chosen const canLocate = IS_TOSS || (typeof navigator !== 'undefined' && 'geolocation' in navigator) const [locateStatus, setLocateStatus] = useState(!landing && (!stored || IS_TOSS) && canLocate ? 'locating' : 'idle') // 지역 페이지에서 고르면 주소도 그 지역 페이지로 바꿔, 공유한 링크가 보던 화면과 같게 한다 const setRegion = useCallback((r: RegionData) => { setRegionState(r) writeStored(r) const next = ownPage(r.code) if (pageRef.current && next && next !== pageRef.current) navigate(`/${dayRef.current}/${next.path}`) }, [navigate]) // quiet 면 못 찾아도 상태를 바꾸지 않는다 (사람이 누른 게 아니라 안내 문구를 띄우지 않음). ask=false 면 토스에서 권한 창 없이, 이미 허용한 사람만 const findNearest = useCallback((apply: (r: RegionData) => void, quiet = false, ask = true) => { const fromCoords = (lat: number, lon: number) => { nearestRegion({ query: { lat, lon } }) .then(({ data: res }) => { if (!res.region) throw new Error('가까운 구를 찾지 못함') setLocateStatus('idle') apply(res.region) }) .catch(() => !quiet && setLocateStatus('error')) } if (IS_TOSS) { tossLocation(ask).then( (loc) => { if (loc === null) setLocateStatus('idle') else if (loc === 'denied') setLocateStatus(quiet ? 'idle' : 'denied') else fromCoords(loc.lat, loc.lon) }, (e: unknown) => { console.error('[region] toss location', e) setLocateStatus(quiet ? 'idle' : 'error') }, ) return } navigator.geolocation.getCurrentPosition( (pos) => fromCoords(pos.coords.latitude, pos.coords.longitude), (err) => !quiet && setLocateStatus(err.code === err.PERMISSION_DENIED ? 'denied' : 'error'), { timeout: 10000, maximumAge: 600000 }, ) }, []) const locate = useCallback((onFound?: () => void) => { if (!canLocate) { setLocateStatus('error') return } setLocateStatus('locating') findNearest((r) => { setRegion(r) track('region_change', { region_name: r.name, method: 'location' }) onFound?.() }) }, [canLocate, findNearest, setRegion]) useEffect(() => { if (!canLocate) return // 처음 온 사람은 위치 권한을 물어 가장 가까운 구로 맞춘다. 토스판은 지역을 고른 적 있어도 권한이 있으면 들어올 때마다 지금 위치로 if (!landing) { const apply = (r: RegionData) => { setRegion(r) track('region_change', { region_name: r.name, method: 'location' }) } if (!stored) findNearest(apply) else if (IS_TOSS) findNearest(apply, false, false) return } // 지역 페이지로 들어오면 그 지역을 보여 준다. 구로 나뉜 시는 위치를 이미 허용했고 그 시 안에 있으면 지금 있는 구로 if (landing.regions.length < 2) return navigator.permissions?.query({ name: 'geolocation' }) .then((s) => { if (s.state !== 'granted') return findNearest((r) => { if (pageRef.current === landing && landing.regions.some((g) => g.code === r.code)) setRegionState(r) }, true) }) .catch((e) => console.warn('위치 권한 상태를 읽지 못함', e)) }, [canLocate, landing, stored, findNearest, setRegion]) const api = useMemo(() => ({ region, setRegion, locate, locateStatus }), [region, setRegion, locate, locateStatus]) return {children} }