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

export type Platform = "web" | "desktop" | "mobile"

const PlatformContext = createContext<Platform>("web")

function isTauri(): boolean {
  return !!(window as unknown as Record<string, unknown>).__TAURI_INTERNALS__
}

export function PlatformProvider({ children }: { children: ReactNode }) {
  const [platform, setPlatform] = useState<Platform>(isTauri() ? "desktop" : "web")

  useEffect(() => {
    if (!isTauri()) return
    let cancelled = false
    ;(async () => {
      try {
        const { platform: osPlatform } = await import("@tauri-apps/plugin-os")
        const p = osPlatform()
        if (!cancelled) {
          setPlatform(p === "android" || p === "ios" ? "mobile" : "desktop")
        }
      } catch {
        // stays "desktop"
      }
    })()
    return () => {
      cancelled = true
    }
  }, [])

  return (
    <PlatformContext.Provider value={platform}>
      {children}
    </PlatformContext.Provider>
  )
}

export function usePlatform(): Platform {
  return useContext(PlatformContext)
}
