// Dreamwell GPU — Skybox Pass
//
// Renders an equirectangular 2D environment map as a fullscreen sky sphere
// behind all scene geometry. Uses an inverted unit cube with view rotation
// only (no translation) so the skybox stays at infinity.
//
// Default: loads the bundled sky panorama JPEG at editor startup.
// The IBL precompute system uses this same texture as environment source
// for diffuse irradiance and specular prefilter cubemaps.
//
// Clean Compute: zero per-frame allocation. Pipeline and bind group cached
// at init. Per-frame cost: one 64-byte uniform write + 36-vertex draw.

use crate::camera::Camera;

/// Skybox uniforms — 64 bytes (mat4x4<f32>).
#[repr(C)]
#[derive(Copy, Clone, Debug, bytemuck::Pod, bytemuck::Zeroable)]
pub struct SkyboxUniforms {
    /// View-projection matrix with translation stripped (rotation only).
    pub view_proj: [f32; 16],
}

/// Skybox render pass. Draws an equirectangular environment map at max depth.
pub struct SkyboxPass {
    pipeline: Option<wgpu::RenderPipeline>,
    uniform_buffer: Option<wgpu::Buffer>,
    bind_group: Option<wgpu::BindGroup>,
    bgl: Option<wgpu::BindGroupLayout>,
    sampler: Option<wgpu::Sampler>,
    env_texture: Option<wgpu::Texture>,
    env_view: Option<wgpu::TextureView>,
    /// Whether the pipeline and resources are initialized.
    pub initialized: bool,
    /// If true, a valid environment texture is bound and the skybox should render.
    pub enabled: bool,
    /// The format the pipeline was compiled for (used to detect format changes).
    compiled_format: Option<wgpu::TextureFormat>,
}

impl SkyboxPass {
    pub fn new() -> Self {
        Self {
            pipeline: None,
            uniform_buffer: None,
            bind_group: None,
            bgl: None,
            sampler: None,
            env_texture: None,
            env_view: None,
            initialized: false,
            enabled: true,
            compiled_format: None,
        }
    }

    /// Initialize the skybox pipeline and bind group layout.
    pub fn init(&mut self, device: &wgpu::Device, target_format: wgpu::TextureFormat) {
        if self.initialized && self.compiled_format == Some(target_format) {
            return;
        }

        let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
            label: Some("skybox.wgsl"),
            source: wgpu::ShaderSource::Wgsl(include_str!("../shaders/skybox.wgsl").into()),
        });

        let bgl = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
            label: Some("skybox_bgl"),
            entries: &[
                wgpu::BindGroupLayoutEntry {
                    binding: 0,
                    visibility: wgpu::ShaderStages::VERTEX,
                    ty: wgpu::BindingType::Buffer {
                        ty: wgpu::BufferBindingType::Uniform,
                        has_dynamic_offset: false,
                        min_binding_size: None,
                    },
                    count: None,
                },
                wgpu::BindGroupLayoutEntry {
                    binding: 1,
                    visibility: wgpu::ShaderStages::FRAGMENT,
                    ty: wgpu::BindingType::Texture {
                        sample_type: wgpu::TextureSampleType::Float { filterable: true },
                        view_dimension: wgpu::TextureViewDimension::D2,
                        multisampled: false,
                    },
                    count: None,
                },
                wgpu::BindGroupLayoutEntry {
                    binding: 2,
                    visibility: wgpu::ShaderStages::FRAGMENT,
                    ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering),
                    count: None,
                },
            ],
        });

        let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
            label: Some("skybox_pipeline_layout"),
            bind_group_layouts: &[Some(&bgl)],
            immediate_size: 0,
        });

        let pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
            label: Some("skybox_pipeline"),
            layout: Some(&pipeline_layout),
            vertex: wgpu::VertexState {
                module: &shader,
                entry_point: Some("vs_main"),
                buffers: &[],
                compilation_options: Default::default(),
            },
            fragment: Some(wgpu::FragmentState {
                module: &shader,
                entry_point: Some("fs_main"),
                targets: &[Some(wgpu::ColorTargetState {
                    format: target_format,
                    blend: None,
                    write_mask: wgpu::ColorWrites::ALL,
                })],
                compilation_options: Default::default(),
            }),
            primitive: wgpu::PrimitiveState {
                topology: wgpu::PrimitiveTopology::TriangleList,
                front_face: wgpu::FrontFace::Ccw,
                cull_mode: None, // Render inside of cube
                ..Default::default()
            },
            depth_stencil: Some(wgpu::DepthStencilState {
                format: wgpu::TextureFormat::Depth32Float,
                depth_write_enabled: Some(false),
                depth_compare: Some(wgpu::CompareFunction::LessEqual),
                stencil: Default::default(),
                bias: Default::default(),
            }),
            multisample: Default::default(),
            multiview_mask: None,
            cache: None,
        });

        let uniform_buffer = device.create_buffer(&wgpu::BufferDescriptor {
            label: Some("skybox_uniforms"),
            size: 64,
            usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
            mapped_at_creation: false,
        });

        let sampler = device.create_sampler(&wgpu::SamplerDescriptor {
            label: Some("skybox_sampler"),
            address_mode_u: wgpu::AddressMode::Repeat,
            address_mode_v: wgpu::AddressMode::ClampToEdge,
            address_mode_w: wgpu::AddressMode::ClampToEdge,
            mag_filter: wgpu::FilterMode::Linear,
            min_filter: wgpu::FilterMode::Linear,
            mipmap_filter: wgpu::MipmapFilterMode::Linear,
            ..Default::default()
        });

        self.pipeline = Some(pipeline);
        self.uniform_buffer = Some(uniform_buffer);
        self.bgl = Some(bgl);
        self.sampler = Some(sampler);
        self.compiled_format = Some(target_format);
        self.initialized = true;

        // Rebuild bind group if env texture was already loaded (format change case).
        if let Some(ref env_view) = self.env_view {
            if let (Some(ref bgl), Some(ref uniform_buf), Some(ref sampler)) =
                (&self.bgl, &self.uniform_buffer, &self.sampler)
            {
                self.bind_group = Some(device.create_bind_group(&wgpu::BindGroupDescriptor {
                    label: Some("skybox_bind_group"),
                    layout: bgl,
                    entries: &[
                        wgpu::BindGroupEntry {
                            binding: 0,
                            resource: uniform_buf.as_entire_binding(),
                        },
                        wgpu::BindGroupEntry {
                            binding: 1,
                            resource: wgpu::BindingResource::TextureView(env_view),
                        },
                        wgpu::BindGroupEntry {
                            binding: 2,
                            resource: wgpu::BindingResource::Sampler(sampler),
                        },
                    ],
                }));
            }
        }
    }

    /// Load a JPEG/PNG image from raw bytes as the environment texture.
    /// Decodes the image, uploads to GPU, and creates the bind group.
    pub fn load_environment_image(&mut self, device: &wgpu::Device, queue: &wgpu::Queue, image_bytes: &[u8]) -> bool {
        let img = match image::load_from_memory(image_bytes) {
            Ok(img) => img.to_rgba8(),
            Err(e) => {
                log::warn!("Skybox: failed to decode image: {e}");
                return false;
            }
        };

        let (width, height) = img.dimensions();
        let texture = device.create_texture(&wgpu::TextureDescriptor {
            label: Some("skybox_env_texture"),
            size: wgpu::Extent3d {
                width,
                height,
                depth_or_array_layers: 1,
            },
            mip_level_count: 1,
            sample_count: 1,
            dimension: wgpu::TextureDimension::D2,
            format: wgpu::TextureFormat::Rgba8UnormSrgb,
            usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
            view_formats: &[],
        });

        queue.write_texture(
            wgpu::TexelCopyTextureInfo {
                texture: &texture,
                mip_level: 0,
                origin: wgpu::Origin3d::ZERO,
                aspect: wgpu::TextureAspect::All,
            },
            &img,
            wgpu::TexelCopyBufferLayout {
                offset: 0,
                bytes_per_row: Some(4 * width),
                rows_per_image: Some(height),
            },
            wgpu::Extent3d {
                width,
                height,
                depth_or_array_layers: 1,
            },
        );

        let view = texture.create_view(&wgpu::TextureViewDescriptor::default());

        // Create bind group
        if let (Some(ref bgl), Some(ref uniform_buf), Some(ref sampler)) =
            (&self.bgl, &self.uniform_buffer, &self.sampler)
        {
            self.bind_group = Some(device.create_bind_group(&wgpu::BindGroupDescriptor {
                label: Some("skybox_bind_group"),
                layout: bgl,
                entries: &[
                    wgpu::BindGroupEntry {
                        binding: 0,
                        resource: uniform_buf.as_entire_binding(),
                    },
                    wgpu::BindGroupEntry {
                        binding: 1,
                        resource: wgpu::BindingResource::TextureView(&view),
                    },
                    wgpu::BindGroupEntry {
                        binding: 2,
                        resource: wgpu::BindingResource::Sampler(sampler),
                    },
                ],
            }));
        }

        self.env_texture = Some(texture);
        self.env_view = Some(view);

        log::info!("Skybox: environment loaded ({width}x{height})");
        true
    }

    /// Render the skybox into the current render pass.
    /// Draws at max depth so it appears behind all geometry.
    pub fn render(&self, queue: &wgpu::Queue, pass: &mut wgpu::RenderPass<'_>, camera: &Camera) {
        if !self.enabled || !self.initialized {
            return;
        }
        let Some(ref pipeline) = self.pipeline else { return };
        let Some(ref bind_group) = self.bind_group else { return };
        let Some(ref uniform_buf) = self.uniform_buffer else {
            return;
        };

        // Strip translation from view matrix — keep only rotation.
        let mut view_no_translate = camera.view_matrix;
        view_no_translate.w_axis.x = 0.0;
        view_no_translate.w_axis.y = 0.0;
        view_no_translate.w_axis.z = 0.0;

        let vp = camera.projection_matrix * view_no_translate;
        let uniforms = SkyboxUniforms {
            view_proj: vp.to_cols_array(),
        };
        queue.write_buffer(uniform_buf, 0, bytemuck::bytes_of(&uniforms));

        pass.set_pipeline(pipeline);
        pass.set_bind_group(0, bind_group, &[]);
        pass.draw(0..36, 0..1);
    }

    /// Destroy GPU resources.
    pub fn destroy(&mut self) {
        if let Some(b) = self.uniform_buffer.take() {
            b.destroy();
        }
        if let Some(t) = self.env_texture.take() {
            t.destroy();
        }
        self.pipeline = None;
        self.bind_group = None;
        self.bgl = None;
        self.sampler = None;
        self.env_view = None;
        self.initialized = false;
    }
}
