import { StyleSheet } from 'react-native'
import { viewports } from '@telus-uds/system-constants'

/**
 * @typedef {import('@telus-uds/system-constants/viewports').Viewport} Viewport
 * @typedef {'row' | 'column' | 'row-reverse' | 'column-reverse'} StackDirection
 * @typedef {Record<Viewport, StackDirection>} StackDirectionByViewport
 */

const rowDirections = ['row', 'row-reverse']

export const selectFlexStyles = ({ alignItems, justifyContent, flexGrow, flexShrink }) => ({
  alignItems,
  justifyContent,
  flexGrow,
  flexShrink
})

/**
 * Maps each viewport's stack direction to the axis a `Spacer` between two stacked items must size,
 * which is the axis the container stacks along rather than the order it stacks in.
 *
 * A `Spacer` sizes one axis only, so a container whose direction is emitted as a media rule needs
 * its spacers to switch axis on that same rule. A spacer left on the direction JavaScript resolved
 * would size height inside a container the rule has already turned into a row, and the gap would
 * collapse until hydration.
 *
 * @param {StackDirectionByViewport} directionByViewport
 * @returns {Record<Viewport, 'row' | 'column'>}
 *
 * @example
 * getSpacerDirectionByViewport({ xs: 'column', sm: 'column', md: 'row-reverse', lg: 'row', xl: 'row' })
 * // => { xs: 'column', sm: 'column', md: 'row', lg: 'row', xl: 'row' }
 */
export const getSpacerDirectionByViewport = (directionByViewport) =>
  viewports.keys.reduce(
    (byViewport, viewport) => ({
      ...byViewport,
      [viewport]: rowDirections.includes(directionByViewport[viewport]) ? 'row' : 'column'
    }),
    {}
  )

export const staticStyles = StyleSheet.create({
  wrap: {
    flexShrink: 1,
    flexWrap: 'wrap',
    alignContent: 'stretch'
  },
  row: {
    flexDirection: 'row'
  },
  'row-reverse': {
    flexDirection: 'row-reverse'
  },
  column: {
    // This is the React Native View default, but also it's very fundamental to the behaviour,
    // so make it explicit and allow it to be tested for.
    flexDirection: 'column'
  },
  'column-reverse': {
    flexDirection: 'column-reverse'
  }
})
