import { useCallback, useEffect, useState } from 'react'
import { Outlet } from 'react-router-dom'
import { supportsFullscreen } from '../lib/platform'
import styles from './AppLayout.module.css'

export function AppLayout() {
  const canFullscreen = supportsFullscreen()
  const [isFullscreen, setIsFullscreen] = useState(!!document.fullscreenElement)

  useEffect(() => {
    if (!canFullscreen) return
    const onChange = () => setIsFullscreen(!!document.fullscreenElement)
    document.addEventListener('fullscreenchange', onChange)
    return () => document.removeEventListener('fullscreenchange', onChange)
  }, [canFullscreen])

  const goFullscreen = useCallback(() => {
    document.documentElement.requestFullscreen().catch(() => {})
  }, [])

  return (
    <div className={styles.shell}>
      <main className={styles.main}>
        <Outlet />
      </main>
      {canFullscreen && !isFullscreen && (
        <button
          type="button"
          className={styles.fullscreenBtn}
          onClick={goFullscreen}
          aria-label="Enter fullscreen"
          title="Enter fullscreen"
        >
          ⛶
        </button>
      )}
    </div>
  )
}
