import { BlurView } from 'expo-blur'
import { Platform, StyleSheet } from 'react-native'
import { useTheme, useThemeName, View } from 'tamagui'

// GlassSurface — the single entry point for every frosted-chrome backdrop
// in the app (menu pills, sticky page headers). Draws the expo-blur layer
// plus a neutral `$surfaceGlassTint` wash so the blur stays saturation-
// neutral and icons drawn in `$onSurfacePrimary` / `$onSurfaceMuted` remain
// legible. Callers own clipping, borders, and positioning — GlassSurface
// only paints the backdrop layers.

// Samsung One UI's compositor renders `dimezisBlurViewSdk31Plus` with
// horizontal banding through the blurred output, and there's no reliable
// runtime signal that distinguishes a "good Android blur" device from a
// "banded Android blur" device. Treat all Android as no-native-blur and
// route every consumer through the opaque `$backgroundMenu` fallback that
// Android < 31 already used.
export const ANDROID_HAS_NATIVE_BLUR = false

export type GlassSurfaceKind =
  // Backdrop for floating chrome (menu pills, sticky headers). Blurs on
  // iOS; opaque-fallback fill on Android (see ANDROID_HAS_NATIVE_BLUR).
  | 'translucent'
  // Parent paints its own `$background`; GlassSurface draws nothing.
  | 'solid'

type AndroidBlurMode =
  // Menu pills: blur on iOS, opaque fallback fill on Android (see
  // ANDROID_HAS_NATIVE_BLUR for the device-coverage rationale).
  | 'auto'
  // Sticky page headers: never blur on Android; parent paints a solid
  // `$background` so the header reads as hard chrome.
  | 'solid'

type GlassSurfaceProps = {
  kind?: GlassSurfaceKind
  intensity?: number
  androidBlur?: AndroidBlurMode
}

export function GlassSurface({
  kind = 'translucent',
  intensity,
  androidBlur = 'auto',
}: GlassSurfaceProps) {
  const theme = useTheme()
  const themeName = useThemeName()
  if (kind === 'solid') return null

  const canBlurOnAndroid = androidBlur === 'auto' && ANDROID_HAS_NATIVE_BLUR
  const showBlur = Platform.OS === 'ios' || canBlurOnAndroid

  // When blur is drawn, paint a neutral `$surfaceGlassTint` wash on top so
  // icons read consistently regardless of the content underneath. When no
  // blur is available (Android < 31 with `auto`, or any Android with
  // `solid`) we skip the overlay entirely — the parent is expected to paint
  // its own opaque fill (`$backgroundMenu` on PillRoot, `$background` on
  // the sticky header), so an additional alpha wash would just dilute it.
  if (!showBlur) return null

  const tintColor = theme.surfaceGlassTint?.val as string

  return (
    <>
      <BlurView
        intensity={intensity ?? (Platform.OS === 'ios' ? 60 : 80)}
        tint={themeName === 'dark' ? 'dark' : 'light'}
        blurMethod="dimezisBlurViewSdk31Plus"
        style={StyleSheet.absoluteFill}
      />
      <View
        pointerEvents="none"
        style={[StyleSheet.absoluteFill, { backgroundColor: tintColor }]}
      />
    </>
  )
}
