import Taro from '@tarojs/taro'
import { Text, View } from '@tarojs/components'
import { useSystemLayout } from '@/hooks/useSystemLayout'
import { ensureProfileReady } from '@/store/session.store'
import { tabs, type MainTabKey } from './tabConfig'
import './index.scss'

interface BottomTabBarProps {
  active: MainTabKey
  // In the single-page host, switching tabs is a state change (no page
  // transition → no flash). Falls back to switchTab if used standalone.
  onSwitch?: (key: MainTabKey) => void
}

export function BottomTabBar({ active, onSwitch }: BottomTabBarProps) {
  const { safeBottom } = useSystemLayout()

  const go = (key: MainTabKey, path: string) => {
    if (key === active) return
    if (onSwitch) {
      onSwitch(key)
      return
    }
    Taro.switchTab({ url: path })
  }

  const renderTab = (index: number) => {
    const tab = tabs[index]
    const activeClass = active === tab.key ? 'bottom-tabbar__item--active' : ''

    return (
      <View className={`bottom-tabbar__item ${activeClass}`} onClick={() => go(tab.key, tab.path)}>
        <View className='bottom-tabbar__icon-wrap'>
          <View className={`bottom-tabbar__icon bottom-tabbar__icon--${tab.key}`} />
          {tab.dot ? <View className='bottom-tabbar__dot' /> : null}
        </View>
        <Text className={`bottom-tabbar__label ${active === tab.key ? 'bottom-tabbar__label--active' : ''}`}>{tab.label}</Text>
      </View>
    )
  }

  const goPublish = async () => {
    if (!(await ensureProfileReady())) return
    Taro.navigateTo({ url: '/pages/publish/index' })
  }

  return (
    <View className='bottom-tabbar' style={{ paddingBottom: `${Math.max(22, safeBottom)}px` }}>
      {renderTab(0)}
      {renderTab(1)}
      <View className='bottom-tabbar__fab' onClick={goPublish}>
        <View className='bottom-tabbar__fab-inner'>
          <View className='bottom-tabbar__fab-icon' />
        </View>
      </View>
      {renderTab(2)}
      {renderTab(3)}
    </View>
  )
}

export default BottomTabBar
