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

/**
 * UIWS 이식 모듈 테마(다크/라이트). 모듈 스코프 — 전역 Mall 테마(관리자 .admin-shell /
 * 스토어프론트 Tailwind)는 건드리지 않는다. data-uiws-theme 속성만 토글하여 var(--uiws-*) 스왑.
 * 영속: localStorage('mall_uiws_theme'). 기본 dark(관리자 셸 정합).
 */
export type ThemeMode = 'dark' | 'light'

interface ThemeCtx {
  theme: ThemeMode
  toggle: () => void
  setTheme: (t: ThemeMode) => void
}

const Ctx = createContext<ThemeCtx>({ theme: 'dark', toggle: () => {}, setTheme: () => {} })

const STORAGE_KEY = 'mall_uiws_theme'

function applyTheme(t: ThemeMode) {
  document.documentElement.setAttribute('data-uiws-theme', t)
}

export function ThemeProvider({ children }: { children: ReactNode }) {
  const [theme, setThemeState] = useState<ThemeMode>(() => {
    const saved = localStorage.getItem(STORAGE_KEY)
    return saved === 'light' ? 'light' : 'dark'
  })

  useEffect(() => {
    applyTheme(theme)
    localStorage.setItem(STORAGE_KEY, theme)
  }, [theme])

  const setTheme = (t: ThemeMode) => setThemeState(t)
  const toggle = () => setThemeState(prev => (prev === 'dark' ? 'light' : 'dark'))

  return <Ctx.Provider value={{ theme, toggle, setTheme }}>{children}</Ctx.Provider>
}

export function useTheme() {
  return useContext(Ctx)
}
