<script setup lang="ts">
import {
  PCFSoftShadowMap,
  CineonToneMapping,
  PMREMGenerator,
  CanvasTexture
} from 'three'

import { GainMapLoader } from '@monogrid/gainmap-js'

const { scene, renderer, camera } = useTresContext()

renderer.value.toneMapping = CineonToneMapping
renderer.value.toneMappingExposure = 1

renderer.value.shadowMap.enabled = true
renderer.value.shadowMap.type = PCFSoftShadowMap

const pmremGenerator = new PMREMGenerator(renderer.value)
pmremGenerator.compileEquirectangularShader()

function createGradientTexture () {
  const canvas = document.createElement('canvas')
  canvas.width = 256
  canvas.height = 256

  const ctx = canvas.getContext('2d')
  if (!ctx) return null

  // Создаем линейный градиент
  const gradient = ctx.createLinearGradient(0, 0, canvas.width, canvas.height)
  gradient.addColorStop(0, '#ff7eb3') // Верхний цвет
  gradient.addColorStop(1, '#4f46e5') // Нижний цвет

  // Заполняем холст градиентом
  ctx.fillStyle = gradient
  ctx.fillRect(0, 0, canvas.width, canvas.height)

  // Создаем текстуру из холста
  return new CanvasTexture(canvas)
}

onMounted(async () => {
  const loader = new GainMapLoader(renderer.value)
  const result = await loader.loadAsync([
    'hdrmaps/hdr.webp',
    'hdrmaps/hdr-gainmap.webp',
    'hdrmaps/hdr.json'
  ])
  if (renderer.value && camera.value) {
    renderer.value.render(scene.value, camera.value)
  }
  const exrCubeRenderTarget = pmremGenerator.fromEquirectangular(
    result.renderTarget.texture
  )
  const newEnvMap = exrCubeRenderTarget ? exrCubeRenderTarget.texture : null

  scene.value.environment = newEnvMap
  scene.value.environmentIntensity = 1.25
  scene.value.environmentRotation.z = 0.25
  result.renderTarget.texture.dispose()
})
</script>
<template></template>
