import { createContext, useContext, useState, useCallback } from 'react'

const AppContext = createContext()

export function AppProvider({ children }) {
  const [windows, setWindows] = useState([])
  const [activeWindow, setActiveWindow] = useState(null)
  const [startMenuOpen, setStartMenuOpen] = useState(false)
  const [sessionActive, setSessionActive] = useState(false)
  const [sessionStartTime, setSessionStartTime] = useState(null)

  const openWindow = useCallback((app) => {
    const id = Date.now()
    const newWindow = {
      id,
      app: app.id,
      title: app.title,
      icon: app.icon,
      x: 100 + (windows.length * 30),
      y: 50 + (windows.length * 30),
      width: app.defaultWidth || 800,
      height: app.defaultHeight || 600,
      minimized: false,
      maximized: false
    }
    setWindows(prev => [...prev, newWindow])
    setActiveWindow(id)
    setStartMenuOpen(false)
  }, [windows.length])

  const closeWindow = useCallback((id) => {
    setWindows(prev => prev.filter(w => w.id !== id))
    if (activeWindow === id) {
      setActiveWindow(null)
    }
  }, [activeWindow])

  const minimizeWindow = useCallback((id) => {
    setWindows(prev => prev.map(w => 
      w.id === id ? { ...w, minimized: true } : w
    ))
    setActiveWindow(null)
  }, [])

  const restoreWindow = useCallback((id) => {
    setWindows(prev => prev.map(w => 
      w.id === id ? { ...w, minimized: false } : w
    ))
    setActiveWindow(id)
  }, [])

  const focusWindow = useCallback((id) => {
    setActiveWindow(id)
    setWindows(prev => prev.map(w => 
      w.id === id ? { ...w, minimized: false } : w
    ))
  }, [])

  const updateWindowPosition = useCallback((id, x, y) => {
    setWindows(prev => prev.map(w => 
      w.id === id ? { ...w, x, y } : w
    ))
  }, [])

  const startSession = useCallback(() => {
    setSessionActive(true)
    setSessionStartTime(new Date())
  }, [])

  const endSession = useCallback(() => {
    setSessionActive(false)
    setSessionStartTime(null)
  }, [])

  return (
    <AppContext.Provider value={{
      windows,
      activeWindow,
      startMenuOpen,
      setStartMenuOpen,
      openWindow,
      closeWindow,
      minimizeWindow,
      restoreWindow,
      focusWindow,
      updateWindowPosition,
      sessionActive,
      sessionStartTime,
      startSession,
      endSession
    }}>
      {children}
    </AppContext.Provider>
  )
}

export function useApp() {
  return useContext(AppContext)
}
