File size: 3,357 Bytes
d15f07c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
import React, { createContext, useContext, useState, useEffect, ReactNode } from 'react'
import { useAuth } from './AuthContext'
import { stateNameToCode } from '../utils/stateMapping'

export type LocationGranularity = 'state' | 'county'

export interface LocationData {
  address?: string
  state: string
  county: string
  city: string
  /** When Nominatim returns a state or county boundary without a city/town. */
  granularity?: LocationGranularity
  school_board?: string
  latitude?: number
  longitude?: number
}

interface LocationContextType {
  location: LocationData | null
  setLocation: (location: LocationData) => void
  clearLocation: () => void
  hasLocation: boolean
}

const LocationContext = createContext<LocationContextType | undefined>(undefined)

export const LocationProvider: React.FC<{ children: ReactNode }> = ({ children }) => {
  const { user, isAuthenticated, isLoading: authLoading } = useAuth()
  const [location, setLocationState] = useState<LocationData | null>(null)

  // Prefer the most recent manual selection from localStorage. If there is no
  // manual selection, wait for AuthContext's asynchronous /auth/me request and
  // then hydrate from the signed-in user's profile.
  useEffect(() => {
    const savedLocation = localStorage.getItem('user_location')
    if (savedLocation) {
      try {
        const parsed = JSON.parse(savedLocation) as LocationData
        
        // Migrate full state names to state codes
        if (parsed.state) {
          parsed.state = stateNameToCode(parsed.state)
        }
        
        setLocationState(parsed)
        
        // Save back the migrated version
        localStorage.setItem('user_location', JSON.stringify(parsed))
        return // A manual selection takes precedence over the profile.
      } catch (e) {
        console.error('Failed to parse saved location:', e)
        // A corrupt value must not permanently block the profile fallback.
        localStorage.removeItem('user_location')
      }
    }
    
    if (authLoading) return

    if (isAuthenticated && user && user.state && user.city) {
      const stateCode = stateNameToCode(user.state)
      
      const profileLocation = {
        state: stateCode,
        county: user.county || '',
        city: user.city,
        school_board: user.school_board,
      }
      
      setLocationState(profileLocation)
    }
  }, [authLoading, isAuthenticated, user])

  const setLocation = (newLocation: LocationData) => {
    setLocationState(newLocation)
    
    // Always save to localStorage (even for authenticated users as a backup)
    localStorage.setItem('user_location', JSON.stringify(newLocation))
  }

  const clearLocation = () => {
    setLocationState(null)
    localStorage.removeItem('user_location')
  }

  const hasLocation =
    location !== null &&
    !!location.state &&
    (!!location.city ||
      location.granularity === 'state' ||
      (location.granularity === 'county' && !!location.county))

  return (
    <LocationContext.Provider value={{ location, setLocation, clearLocation, hasLocation }}>
      {children}
    </LocationContext.Provider>
  )
}

export const useLocation = () => {
  const context = useContext(LocationContext)
  if (context === undefined) {
    throw new Error('useLocation must be used within a LocationProvider')
  }
  return context
}