import { useSyncExternalStore } from 'react'
import { acknowledge, PermissionDisclosureStore } from 'src/state/permissionDisclosure'
import { Adapt, AlertDialog, Button, Sheet, XStack, YStack } from 'tamagui'

const COPY = {
  camera: {
    title: 'Camera access',
    body: 'Halflight uses the camera so you can take photos and record videos to post to your Pixelfed feed and share as stories. The next prompt is the system permission — you can deny it, and you can change your mind later in system Settings.',
  },
  microphone: {
    title: 'Microphone access',
    body: 'Halflight uses the microphone to record audio with story videos you capture in the app. The next prompt is the system permission — you can deny it, and you can change your mind later in system Settings.',
  },
} as const

// Android Prominent Disclosure modal (D.2). Mounted once at the root layout
// in `_layout.tsx`. Subscribes to PermissionDisclosureStore; only renders
// when an Android-side caller has invoked `disclose(kind)`. iOS short-
// circuits before reaching this component (the store resolves immediately).
export function PermissionDisclosure() {
  const state = useSyncExternalStore(
    PermissionDisclosureStore.subscribe,
    PermissionDisclosureStore.getSnapshot,
    PermissionDisclosureStore.getSnapshot
  )

  if (!state.visible || !state.kind) return null
  const copy = COPY[state.kind]

  const content = (
    <>
      <AlertDialog.Title>{copy.title}</AlertDialog.Title>
      <AlertDialog.Description>{copy.body}</AlertDialog.Description>
      <XStack gap="$2" justifyContent="flex-end">
        <AlertDialog.Action asChild displayWhenAdapted>
          <Button onPress={acknowledge}>Continue</Button>
        </AlertDialog.Action>
      </XStack>
    </>
  )

  return (
    <AlertDialog
      open
      onOpenChange={(open) => {
        if (!open) acknowledge()
      }}
    >
      <Adapt when="sm" platform="touch">
        <Sheet modal dismissOnSnapToBottom>
          <Sheet.Frame padding="$4" gap="$3">
            <Adapt.Contents />
          </Sheet.Frame>
          <Sheet.Overlay
            transition="quick"
            enterStyle={{ opacity: 0 }}
            exitStyle={{ opacity: 0 }}
          />
        </Sheet>
      </Adapt>

      <AlertDialog.Portal>
        <AlertDialog.Overlay
          key="overlay"
          transition="quick"
          enterStyle={{ opacity: 0 }}
          exitStyle={{ opacity: 0 }}
        />
        <AlertDialog.Content
          key="content"
          transition="quick"
          enterStyle={{ opacity: 0, scale: 0.95 }}
          exitStyle={{ opacity: 0, scale: 0.95 }}
        >
          <YStack gap="$3">{content}</YStack>
        </AlertDialog.Content>
      </AlertDialog.Portal>
    </AlertDialog>
  )
}
