import { useEffect, useRef, useState } from 'react'
import { useDidShow } from '@tarojs/taro'
import { View } from '@tarojs/components'
import BottomTabBar from '@/components/navigation/BottomTabBar'
import type { MainTabKey } from '@/components/navigation/BottomTabBar/tabConfig'
import PlazaView from '@/pages/plaza/index'
import NearbyView from '@/pages/nearby/index'
import MessagesView from '@/pages/messages/index'
import ProfileView from '@/pages/profile/index'
import { consumeRequestedTab, onRequestedTab } from '@/store/homeTab'
import './index.scss'

// Single-page host for the four main tabs. Switching tabs is a state change (not
// a page transition), so there is no switchTab transition frame — which is what
// caused the white flash. Tabs are lazily mounted on first visit and then kept
// alive (hidden, not unmounted) so scroll position and loaded data survive.

export default function HomePage() {
  const [active, setActive] = useState<MainTabKey>('plaza')
  const [visited, setVisited] = useState<Record<MainTabKey, boolean>>({
    plaza: true,
    nearby: false,
    messages: false,
    profile: false
  })
  const [showTick, setShowTick] = useState(0)
  const firstShow = useRef(true)

  const switchTo = (key: MainTabKey) => {
    setVisited(prev => (prev[key] ? prev : { ...prev, [key]: true }))
    setActive(key)
  }

  useDidShow(() => {
    // Skip the initial show — the active tab loads on mount.
    if (firstShow.current) {
      firstShow.current = false
      return
    }
    // Returning from a secondary page (publish/detail/edit): honour a requested
    // tab, then bump showTick so the active tab can refresh if stale.
    const requested = consumeRequestedTab()
    if (requested) switchTo(requested)
    setShowTick(tick => tick + 1)
  })

  useEffect(() => onRequestedTab(switchTo), [])

  const tabStyle = (key: MainTabKey) => ({ display: active === key ? 'block' : 'none' } as const)

  return (
    <View className='home'>
      {visited.plaza ? (
        <View className='home__tab' style={tabStyle('plaza')}>
          <PlazaView active={active === 'plaza'} showTick={showTick} />
        </View>
      ) : null}
      {visited.nearby ? (
        <View className='home__tab' style={tabStyle('nearby')}>
          <NearbyView active={active === 'nearby'} showTick={showTick} />
        </View>
      ) : null}
      {visited.messages ? (
        <View className='home__tab' style={tabStyle('messages')}>
          <MessagesView active={active === 'messages'} showTick={showTick} />
        </View>
      ) : null}
      {visited.profile ? (
        <View className='home__tab' style={tabStyle('profile')}>
          <ProfileView active={active === 'profile'} showTick={showTick} />
        </View>
      ) : null}
      <BottomTabBar active={active} onSwitch={switchTo} />
    </View>
  )
}
