import sharp from 'sharp'

interface Props {
  src: string
  size?: number
  alt?: string
}

const convertImage = async (props: Props) => {
  const webp = await sharp(`src/assets/images/${props.src}`).webp({ quality: 75 }).resize(props.size).toBuffer()
  await sharp(webp).toFile(`src/assets/compressed-images/${props.src.split('.').slice(0, -1).join('.')}.webp`)

  const avif = await sharp(`src/assets/images/${props.src}`).avif({ quality: 60 }).resize(props.size).toBuffer()
  await sharp(avif).toFile(`src/assets/compressed-images/${props.src.split('.').slice(0, -1).join('.')}.avif`)
}

export default (props: Props) => {
  convertImage(props)

  return (
    <>
      <picture class="fullscreen">
        <source srcset={`src/assets/compressed-images/${props.src.split('.').slice(0, -1).join('.')}.avif`} type="image/avif" />
        <source srcset={`src/assets/compressed-images/${props.src.split('.').slice(0, -1).join('.')}.webp`} type="image/webp" />
        <img src={`src/assets/compressed-images/${props.src.split('.').slice(0, -1).join('.')}.webp`} width={props.size} height="auto" decoding="async" loading="lazy" alt={props.alt} />
      </picture>
    </>
  )
}
