import {Dimensions, PixelRatio, StyleSheet, TextStyle} from 'react-native';
import {getApiLevelSync} from 'react-native-device-info';
import {isAndroid} from '@shared/utils';

import {getFontStyle} from './utils';
import {TypographyVariant} from './interfaces';

const {width} = Dimensions.get('window');
const scale = PixelRatio.get();
const pixelWidth = width * scale;
const apiLevel = getApiLevelSync();
const shouldAvoidLetterSpacing =
  isAndroid && apiLevel >= 30 && apiLevel <= 33 && pixelWidth <= 720;
const LETTER_SPACING = shouldAvoidLetterSpacing ? undefined : 0.2;

// Every named variant is required to define fontSize and lineHeight so
// consumers can derive layout metrics (e.g. inline-icon vertical offsets)
// without falling back to `?? <magic>`. Spreading `getFontStyle()` widens
// these fields to optional, so we re-narrow them here.
type TypographyStyleMap = {
  [K in TypographyVariant]: TextStyle & {fontSize: number; lineHeight: number};
};

export const TYPOGRAPHY_STYLES: TypographyStyleMap = StyleSheet.create({
  xxxs: {
    ...getFontStyle('regular'),
    fontSize: 10,
    letterSpacing: LETTER_SPACING,
    lineHeight: 14,
  },
  xxs: {
    ...getFontStyle('regular'),
    fontSize: 12,
    letterSpacing: LETTER_SPACING,
    lineHeight: 16.8,
  },
  xs: {
    ...getFontStyle('regular'),
    fontSize: 14,
    letterSpacing: LETTER_SPACING,
    lineHeight: 19.6,
  },
  s: {
    ...getFontStyle('regular'),
    fontSize: 16,
    letterSpacing: LETTER_SPACING,
    lineHeight: 22.4,
  },
  m: {
    ...getFontStyle('regular'),
    fontSize: 18,
    letterSpacing: LETTER_SPACING,
    lineHeight: 25.2,
  },
  l: {
    ...getFontStyle('regular'),
    fontSize: 24,
    letterSpacing: LETTER_SPACING,
    lineHeight: 33.6,
  },
  xl: {
    ...getFontStyle('regular'),
    fontSize: 32,
    letterSpacing: LETTER_SPACING,
    lineHeight: 41.6,
  },
  xxl: {
    ...getFontStyle('regular'),
    fontSize: 36,
    letterSpacing: LETTER_SPACING,
    lineHeight: 50.4,
  },
});
