import { useLayoutEffect } from 'preact/hooks'
import { ValidationError } from '#amidala/main/routing/error-handler.js'
import h from '#amidala/main/shared/h.js'
import usePersistentState from '#amidala/main/shared/use-persistent-state.js'

// 100 days in milliseconds.
const EXPERIMENT_RETENTION = 8_640_000_000
const EXPERIMENTS_KEY = 'experiments'

// Randomly show one of the children.
export function ABTest ({ _model, children, ...props }) {
  const { title } = _model
  if (!title) {
    throw new ValidationError()
  }

  const [experiments, setExperiments] = usePersistentState(EXPERIMENTS_KEY, {})

  useLayoutEffect(() => {
    setExperiments(data => {
      // Clean expired experiments.
      for (const key in data) {
        if (new Date(data[key].date).getTime() + EXPERIMENT_RETENTION < Date.now()) {
          delete data[key]
        }
      }

      // Initialize new experiment.
      data[title] ??= {
        // In this case, Math.random() is appropriate and safe as it not relevant for security
        // eslint-disable-next-line sonarjs/pseudo-random
        index: Math.floor(Math.random() * (children?.length ?? 0)),
        date: new Date().toISOString()
      }

      return data
    })
  }, [title])

  const experiment = experiments[title]
  return experiment && h('div', {
    ...props,
    'data-experiment': `${title} | ${experiment.index + 1}`,
    className: 'h-full',
    children: children[experiment.index]
  })
}
