import { useEffect } from 'react'
import { useWaste } from './store'
import { Onboarding } from './pages/Onboarding'
import { Chat } from './pages/Chat'
import './App.css'

const isLocal = window.location.hostname === 'localhost' || window.location.hostname === '127.0.0.1'
const DAEMON_WS = import.meta.env.VITE_DAEMON_WS ?? 'ws://127.0.0.1:17338'
const cfg = (window as unknown as { WASTE_CONFIG?: { signalURL?: string } }).WASTE_CONFIG
// Use browser mode if a signal URL is configured, even on localhost
const useBrowser = !isLocal || !!cfg?.signalURL

// Wails runtime is injected at /wails/runtime.js when running inside the desktop app.
// EventsOn/EventsOff are no-ops in plain browser mode.
type WailsRuntime = { EventsOn: (event: string, cb: (data: unknown) => void) => void }
const wails = (window as unknown as { runtime?: WailsRuntime }).runtime

function useWailsNotifications() {
  useEffect(() => {
    if (!wails) return

    const handler = (data: unknown) => {
      const { title, body } = data as { title: string; body: string }
      if (Notification.permission === 'granted') {
        new Notification(title, { body })
      } else if (Notification.permission !== 'denied') {
        Notification.requestPermission().then(p => {
          if (p === 'granted') new Notification(title, { body })
        })
      }
    }

    wails.EventsOn('notify', handler)
    return () => {
      // EventsOff added in Wails v2.4; guard in case of older runtime.
      ;(window as unknown as { runtime?: { EventsOff?: (...e: string[]) => void } })
        .runtime?.EventsOff?.('notify')
    }
  }, [])
}

export default function App() {
  const { connect, connectBrowser, daemonStatus, localPeer } = useWaste()

  useEffect(() => {
    if (useBrowser) {
      connectBrowser()
    } else {
      connect(DAEMON_WS)
    }
  }, [connect, connectBrowser])

  useWailsNotifications()

  if (daemonStatus !== 'connected' || !localPeer) {
    return <Onboarding status={daemonStatus} />
  }

  return <Chat />
}
