import { useSyncExternalStore } from 'react'
import { StyleSheet } from 'react-native'
import { AccountStore } from 'src/state/accountStore'
import { Spinner, View } from 'tamagui'
import UserAvatar from './common/UserAvatar'
import { BodyText, FootnoteText } from './ui/Typography'

// AccountSwitchOverlay — Phase 6 §11.5
//
// Mounted once at the root layout. Shows a centered spinner with the
// destination account's avatar + handle while a user-initiated switch is
// in flight. The "switch" itself is local (just a pointer flip), so the
// overlay's job is purely intent-feedback: reassure the user the tap
// landed before the next paint shows different content. AccountStore owns
// the on/off state — this component is a passive subscriber.
//
// Why a full-screen overlay rather than a Sheet/Dialog: Sheets imply user
// interaction and dialogs need dismiss controls; this is a non-interactive
// status preview that should auto-dismiss on its own. Plain absolutely-
// positioned YStack matches that semantic.
export function AccountSwitchOverlay() {
  const isSwitching = useSyncExternalStore(
    AccountStore.subscribeSwitch,
    AccountStore.isSwitching,
    AccountStore.isSwitching
  )

  // Read the destination eagerly each render — it's the active account at
  // this moment because beginSwitch flipped the pointer first. If the user
  // somehow triggers a second switch mid-overlay, the new destination
  // simply replaces the displayed avatar.
  const account = useSyncExternalStore(
    AccountStore.subscribe,
    AccountStore.activeAccount,
    AccountStore.activeAccount
  )

  if (!isSwitching || !account) return null

  return (
    <View
      style={[StyleSheet.absoluteFill, { backgroundColor: 'rgba(0,0,0,0.45)' }]}
      alignItems="center"
      justifyContent="center"
      pointerEvents="auto"
      accessibilityViewIsModal
      accessibilityLabel={`Switching to ${account.acct}`}
    >
      <View
        backgroundColor="$backgroundSecondary"
        borderRadius="$6"
        paddingVertical="$5"
        paddingHorizontal="$6"
        alignItems="center"
        gap="$3"
        minWidth={220}
      >
        <UserAvatar
          url={account.avatarUrl}
          size="lg"
          initial={account.displayName || account.username}
        />
        <BodyText emphasis="strong">{account.displayName || account.username}</BodyText>
        <FootnoteText tone="secondary">@{account.acct}</FootnoteText>
        <Spinner color="$color" />
      </View>
    </View>
  )
}
