import { CharCount } from 'src/components/ui'
import { Input, useTheme, XStack } from 'tamagui'

// Compose Redesign Phase 3 §3.3 — content-warning text input. Renders above
// the caption when `sensitive` is on; the sensitive flag is the carrier and
// the CW text is the human-facing string. Pixelfed caps `spoiler_text` at
// 140 chars (`ApiV1Controller.php:3735`, hardcoded server-side); Mastodon
// has no hard cap on `spoiler_text` so the counter is omitted on that path.
//
// `direct` (DM) is not part of the visibility surface (Pixelfed 400-rejects
// it), so the only branch the consumer cares about is account.type — the
// 140 cap applies on Pixelfed regardless of scope.

type Props = {
  value: string
  onChangeText: (next: string) => void
  /** When non-null, render the counter and pass the value to <Input maxLength>.
   *  Null = no hard cap (Mastodon path); the input still renders but the
   *  counter is hidden. */
  maxLength: number | null
}

export function ComposerCWInput({ value, onChangeText, maxLength }: Props) {
  const theme = useTheme()
  const overLimit = maxLength !== null && value.length > maxLength
  return (
    <XStack
      mt="$2"
      gap="$2"
      alignItems="center"
      borderWidth={1}
      borderRadius={10}
      borderColor={overLimit ? '$colorDanger' : theme.borderColor.val}
      bg={theme.backgroundTertiary.val}
      pr="$3"
    >
      <Input
        flex={1}
        size="$4"
        bg="transparent"
        borderWidth={0}
        color={theme.color.val}
        placeholderTextColor={theme.colorTertiary.val as any}
        placeholder="Add a content warning (optional)"
        value={value}
        onChangeText={onChangeText}
        maxLength={maxLength ?? undefined}
        autoCapitalize="sentences"
        accessibilityLabel="Content warning"
      />
      {maxLength !== null ? (
        <CharCount
          current={value.length}
          max={maxLength}
          tone={overLimit ? 'danger' : 'default'}
        />
      ) : null}
    </XStack>
  )
}
