import React, { useMemo } from 'react'

import { ScreenReaderOnly } from '../styled'

import { RedactOverlay } from './style'


const addJitter = (v: number) => v + Math.random() * 1.15
const stringifyWithJitter = ([x, y]: [number, number]) => `${addJitter(x)},${addJitter(y)}`

export type RedactableTextProps = {
  children: string
  redact?: boolean
}

export const RedactableText = ({ children: text, redact }: RedactableTextProps) => {
  const initiallyRedacted = useMemo(() => redact, [])
  const points = useMemo(
    () =>
      [
        [2, 2],
        [32, 1.5],
        [58, 2.5],
        [90, 2],
        [142, 1],
        [140.5, 8],
        [139, 20],
        [85, 19],
        [65, 19.5],
        [28, 20],
        [3, 19],
        [2.5, 8]
      ].map(stringifyWithJitter),
    []
  )

  const svgData = useMemo(
    () =>
      btoa(`
    <svg
      xmlns='http://www.w3.org/2000/svg'
      viewBox='0 0 144 22'
      preserveAspectRatio='none'>
      <path style='fill: #989898' d='M ${points.join(' ')} Z' />
    </svg>
  `),
    [points]
  )

  return (
    <div style={{ position: 'relative', userSelect: redact ? 'none' : void 0 }}>
      <span aria-hidden={redact}>{text}</span>
      <RedactOverlay
        overlayImg={`data:image/svg+xml;base64,${svgData}`}
        initiallyRedacted={initiallyRedacted}
        currentlyRedacted={redact} />
      {redact && <ScreenReaderOnly>REDACTED</ScreenReaderOnly>}
    </div>
  )
}
