<script setup lang="ts">
import { onMounted, render, watch } from 'vue';

import { ACESFilmicToneMapping, Color, Fog, PMREMGenerator, SRGBColorSpace } from 'three';
import { GainMapLoader } from '@monogrid/gainmap-js'
import { useTresContext } from '@tresjs/core';

import hdr_gainmap from '../../assets/promo/hdr/hdr-gainmap.webp'
import hdr_json from '../../assets/promo/hdr/hdr.json?url'
import hdr_webp from '../../assets/promo/hdr/hdr.webp'
import { IMAGE_URL, PROMOBG } from '../../constants';

const props = defineProps(['hdr_webp', 'hdr_gainmap', 'hdr_json', 'env_displacementmap', 'env_normalmap', 'clear_color', 'focus'])
const { renderer, scene } = useTresContext()

const k = { start: 0.5, end: 4.5 }

renderer.value.outputColorSpace = SRGBColorSpace;
renderer.value.toneMapping = ACESFilmicToneMapping;
renderer.value.toneMappingExposure = 1.25;
renderer.value.setPixelRatio((window.devicePixelRatio || 1) * 2)

const type = 'canvas'
const loadEnv = async () => {
    try {
        const loader = new GainMapLoader(renderer.value)
        const result = await loader.loadAsync([
            props.hdr_webp ? `${IMAGE_URL}/${props.hdr_webp}` : hdr_webp,
            props.hdr_gainmap ? `${IMAGE_URL}/${props.hdr_gainmap}` : hdr_gainmap,
            props.hdr_json ? `${IMAGE_URL}/${props.hdr_json}` : hdr_json,
        ])
        const pmremGenerator = new PMREMGenerator(renderer.value);
        pmremGenerator.compileEquirectangularShader();

        const exrCubeRenderTarget = pmremGenerator.fromEquirectangular(result.renderTarget.texture);
        const newEnvMap = exrCubeRenderTarget ? exrCubeRenderTarget.texture : null;

        // scene.value.background = exrCubeRenderTarget.texture 
        scene.value.environment = newEnvMap
        scene.value.environmentIntensity = 1

        result.renderTarget.texture.dispose();
    } catch (error) {
        console.log(error)
    }

    const c = new Color()
    c.set(props.clear_color || PROMOBG)
    renderer.value.setClearColor(c)
    scene.value.fog = new Fog(c, props.focus * k.start, props.focus * k.end)

    document.documentElement.style.setProperty('--primary-color', props.clear_color)
}

loadEnv()

watch(() => props, () => {
    loadEnv()
}, { deep: true })
</script>
<template></template>