import { createContext, useContext, useEffect, useState, ReactNode, Dispatch, SetStateAction } from 'react'

// 진입 ZIP/매장 선택 컨텍스트 (Floom 패턴) + 고객 토큰 상태
interface ShopState {
  zip: string
  storeId: number | null
  storeName: string
  setZone: (zip: string, storeId: number, storeName: string) => void
  clearZone: () => void
  custToken: string | null
  setCustToken: (t: string | null) => void
  cartCount: number
  setCartCount: Dispatch<SetStateAction<number>>
}
const Ctx = createContext<ShopState>(null as any)

export function ShopProvider({ children }: { children: ReactNode }) {
  const [zip, setZip] = useState(() => localStorage.getItem('mall_zip') || '')
  const [storeId, setStoreId] = useState<number | null>(() => {
    const v = localStorage.getItem('mall_store_id'); return v ? Number(v) : null
  })
  const [storeName, setStoreName] = useState(() => localStorage.getItem('mall_store_name') || '')
  const [custToken, setCustTokenState] = useState<string | null>(() => localStorage.getItem('mall_token'))
  const [cartCount, setCartCount] = useState(0)

  const setZone = (z: string, sid: number, sname: string) => {
    setZip(z); setStoreId(sid); setStoreName(sname)
    localStorage.setItem('mall_zip', z)
    localStorage.setItem('mall_store_id', String(sid))
    localStorage.setItem('mall_store_name', sname)
  }
  const clearZone = () => {
    setZip(''); setStoreId(null); setStoreName('')
    localStorage.removeItem('mall_zip'); localStorage.removeItem('mall_store_id'); localStorage.removeItem('mall_store_name')
  }
  const setCustToken = (t: string | null) => {
    setCustTokenState(t)
    if (t) localStorage.setItem('mall_token', t); else localStorage.removeItem('mall_token')
  }

  useEffect(() => {
    const sync = () => setCustTokenState(localStorage.getItem('mall_token'))
    window.addEventListener('storage', sync)
    return () => window.removeEventListener('storage', sync)
  }, [])

  return (
    <Ctx.Provider value={{ zip, storeId, storeName, setZone, clearZone, custToken, setCustToken, cartCount, setCartCount }}>
      {children}
    </Ctx.Provider>
  )
}
export const useShop = () => useContext(Ctx)

export const money = (n?: number) => `$${(Number(n) || 0).toFixed(2)}`
