import { useMemo } from 'react'
import Taro from '@tarojs/taro'

export interface SystemLayout {
  statusBarHeight: number
  navHeight: number
  menuRight: number
  safeBottom: number
}

// Prefer the split window-info API (base library 2.20+); fall back to the
// deprecated getSystemInfoSync on older clients.
function readWindowInfo(): any {
  const t = Taro as any
  if (typeof t.getWindowInfo === 'function') return t.getWindowInfo()
  return Taro.getSystemInfoSync()
}

export function useSystemLayout(): SystemLayout {
  return useMemo(() => {
    try {
      const system = readWindowInfo()
      const menu = Taro.getMenuButtonBoundingClientRect()
      const statusBarHeight = system.statusBarHeight || 0
      const navHeight = Math.max(54, menu.bottom + 8)
      const screenHeight = system.screenHeight || system.windowHeight || 0
      const safeBottom = Math.max(0, screenHeight - (system.safeArea?.bottom || screenHeight))

      return {
        statusBarHeight,
        navHeight,
        menuRight: Math.max(16, (system.windowWidth || 390) - menu.left + 8),
        safeBottom
      }
    } catch {
      return {
        statusBarHeight: 24,
        navHeight: 54,
        menuRight: 96,
        safeBottom: 20
      }
    }
  }, [])
}

