// Translucency Volume — 3D irradiance volume for translucent surface lighting.
//
// A froxel-style 3D volume (Rgba16Float, 64x64x32) that stores indirect
// lighting samples from the SHaRC radiance cache. Translucent surfaces
// sample this volume instead of the screen-space GI output.
//
// Two compute passes:
//   1. Injection — fills voxels with ambient/indirect radiance estimates.
//   2. Query — PBR shader samples the volume at surface world position.
//
// The injection pass writes into the volume texture. The PBR shader reads
// the volume via a sampled texture binding (separate from the storage view).

/// Default volume resolution: 64x64x32 voxels.
pub const DEFAULT_RESOLUTION: [u32; 3] = [64, 64, 32];

/// Default world half-extent in units.
pub const DEFAULT_WORLD_EXTENT: f32 = 50.0;

/// GPU uniforms for the translucency GI shader (must be #[repr(C)] + Pod + Zeroable, 48 bytes).
#[repr(C)]
#[derive(Copy, Clone, Debug, bytemuck::Pod, bytemuck::Zeroable)]
pub struct TranslucencyVolumeUniforms {
    /// Volume world-space bounds: min corner.
    pub volume_min: [f32; 3],
    pub _pad0: f32,
    /// Volume world-space bounds: max corner.
    pub volume_max: [f32; 3],
    pub _pad1: f32,
    /// Volume resolution.
    pub resolution: [u32; 3],
    /// Current frame index for temporal accumulation.
    pub frame_index: u32,
}

/// Configuration for the translucency volume.
#[derive(Debug, Clone)]
pub struct TranslucencyVolumeConfig {
    /// Volume resolution in voxels. Default: [64, 64, 32].
    pub resolution: [u32; 3],
    /// Half-size of volume in world units, centered on camera. Default: 50.0.
    pub world_extent: f32,
}

impl Default for TranslucencyVolumeConfig {
    fn default() -> Self {
        Self {
            resolution: DEFAULT_RESOLUTION,
            world_extent: DEFAULT_WORLD_EXTENT,
        }
    }
}

/// Translucency GI Volume — 3D irradiance volume for indirect lighting on translucent surfaces.
///
/// Injection pass fills the volume with ambient radiance estimates at voxel world positions.
/// The PBR shader samples the volume via `volume_view()` + `sampler()` bindings for
/// translucent surface indirect lighting, replacing screen-space GI for those surfaces.
pub struct TranslucencyVolume {
    pub enabled: bool,
    volume_texture: Option<wgpu::Texture>,
    volume_view: Option<wgpu::TextureView>,
    uniform_buffer: Option<wgpu::Buffer>,
    inject_pipeline: Option<wgpu::ComputePipeline>,
    inject_bgl: Option<wgpu::BindGroupLayout>,
    sampler: Option<wgpu::Sampler>,
    config: TranslucencyVolumeConfig,
    frame_index: u32,
    initialized: bool,
}

impl Default for TranslucencyVolume {
    fn default() -> Self {
        Self {
            enabled: false,
            volume_texture: None,
            volume_view: None,
            uniform_buffer: None,
            inject_pipeline: None,
            inject_bgl: None,
            sampler: None,
            config: TranslucencyVolumeConfig::default(),
            frame_index: 0,
            initialized: false,
        }
    }
}

impl TranslucencyVolume {
    /// Create a translucency volume with the given configuration, enabled by default.
    pub fn new(config: TranslucencyVolumeConfig) -> Self {
        Self {
            enabled: true,
            config,
            ..Default::default()
        }
    }

    /// Initialize GPU resources: volume texture, uniform buffer, sampler.
    /// Does not create pipelines (call `create_pipelines` separately).
    pub fn init(&mut self, device: &wgpu::Device) {
        if self.initialized {
            return;
        }

        let [w, h, d] = self.config.resolution;
        let format = wgpu::TextureFormat::Rgba16Float;

        // 3D volume texture — storage for injection, sampled for PBR reads.
        let volume = device.create_texture(&wgpu::TextureDescriptor {
            label: Some("translucency_volume"),
            size: wgpu::Extent3d {
                width: w,
                height: h,
                depth_or_array_layers: d,
            },
            mip_level_count: 1,
            sample_count: 1,
            dimension: wgpu::TextureDimension::D3,
            format,
            usage: wgpu::TextureUsages::STORAGE_BINDING | wgpu::TextureUsages::TEXTURE_BINDING,
            view_formats: &[],
        });
        self.volume_view = Some(volume.create_view(&wgpu::TextureViewDescriptor::default()));
        self.volume_texture = Some(volume);

        // Uniform buffer
        if self.uniform_buffer.is_none() {
            self.uniform_buffer = Some(device.create_buffer(&wgpu::BufferDescriptor {
                label: Some("translucency_volume_uniforms"),
                size: std::mem::size_of::<TranslucencyVolumeUniforms>() as u64,
                usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
                mapped_at_creation: false,
            }));
        }

        // Trilinear sampler for smooth volume lookups in PBR shader.
        if self.sampler.is_none() {
            self.sampler = Some(device.create_sampler(&wgpu::SamplerDescriptor {
                label: Some("translucency_volume_sampler"),
                mag_filter: wgpu::FilterMode::Linear,
                min_filter: wgpu::FilterMode::Linear,
                mipmap_filter: wgpu::MipmapFilterMode::Nearest,
                address_mode_u: wgpu::AddressMode::ClampToEdge,
                address_mode_v: wgpu::AddressMode::ClampToEdge,
                address_mode_w: wgpu::AddressMode::ClampToEdge,
                ..Default::default()
            }));
        }

        self.initialized = true;

        log::info!(
            "Translucency volume initialized ({}x{}x{}, extent={:.0})",
            w,
            h,
            d,
            self.config.world_extent,
        );
    }

    /// Compile the translucency_gi.wgsl shader and create the injection compute pipeline.
    pub fn create_pipelines(&mut self, device: &wgpu::Device) {
        let format = wgpu::TextureFormat::Rgba16Float;

        // Injection bind group layout: uniforms + storage write volume.
        let inject_bgl = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
            label: Some("translucency_inject_bgl"),
            entries: &[
                wgpu::BindGroupLayoutEntry {
                    binding: 0,
                    visibility: wgpu::ShaderStages::COMPUTE,
                    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::COMPUTE,
                    ty: wgpu::BindingType::StorageTexture {
                        access: wgpu::StorageTextureAccess::WriteOnly,
                        format,
                        view_dimension: wgpu::TextureViewDimension::D3,
                    },
                    count: None,
                },
            ],
        });

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

        let layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
            label: Some("translucency_inject_layout"),
            bind_group_layouts: &[Some(&inject_bgl)],
            immediate_size: 0,
        });

        self.inject_pipeline = Some(device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor {
            label: Some("translucency_inject"),
            layout: Some(&layout),
            module: &shader,
            entry_point: Some("translucency_inject"),
            compilation_options: Default::default(),
            cache: None,
        }));

        self.inject_bgl = Some(inject_bgl);

        log::info!("Translucency volume pipeline created");
    }

    /// Dispatch the injection compute pass.
    ///
    /// Fills volume voxels with ambient/indirect radiance. The volume is centered
    /// on `camera_pos` with extent from config. Each voxel receives a sky+ground
    /// gradient probe, temporally accumulated at 80/20.
    pub fn inject(
        &mut self,
        device: &wgpu::Device,
        queue: &wgpu::Queue,
        encoder: &mut wgpu::CommandEncoder,
        camera_pos: [f32; 3],
    ) {
        if !self.enabled || !self.initialized {
            return;
        }
        let Some(ref inject_pipe) = self.inject_pipeline else {
            return;
        };
        let Some(ref inject_bgl) = self.inject_bgl else { return };
        let Some(ref uniform_buf) = self.uniform_buffer else {
            return;
        };
        let Some(ref volume_view) = self.volume_view else {
            return;
        };

        let ext = self.config.world_extent;
        let [rx, ry, rz] = self.config.resolution;

        let uniforms = TranslucencyVolumeUniforms {
            volume_min: [camera_pos[0] - ext, camera_pos[1] - ext, camera_pos[2] - ext],
            _pad0: 0.0,
            volume_max: [camera_pos[0] + ext, camera_pos[1] + ext, camera_pos[2] + ext],
            _pad1: 0.0,
            resolution: [rx, ry, rz],
            frame_index: self.frame_index,
        };
        queue.write_buffer(uniform_buf, 0, bytemuck::bytes_of(&uniforms));

        let bg = device.create_bind_group(&wgpu::BindGroupDescriptor {
            label: Some("translucency_inject_bg"),
            layout: inject_bgl,
            entries: &[
                wgpu::BindGroupEntry {
                    binding: 0,
                    resource: uniform_buf.as_entire_binding(),
                },
                wgpu::BindGroupEntry {
                    binding: 1,
                    resource: wgpu::BindingResource::TextureView(volume_view),
                },
            ],
        });

        {
            let mut pass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor {
                label: Some("translucency_inject"),
                timestamp_writes: None,
            });
            pass.set_pipeline(inject_pipe);
            pass.set_bind_group(0, &bg, &[]);
            pass.dispatch_workgroups(rx.div_ceil(4), ry.div_ceil(4), rz.div_ceil(4));
        }

        self.frame_index = self.frame_index.wrapping_add(1);
    }

    /// Get the volume texture view for binding in the PBR shader (sampled read).
    pub fn volume_view(&self) -> Option<&wgpu::TextureView> {
        self.volume_view.as_ref()
    }

    /// Get the trilinear sampler for the volume texture.
    pub fn sampler(&self) -> Option<&wgpu::Sampler> {
        self.sampler.as_ref()
    }

    /// Current configuration.
    pub fn config(&self) -> &TranslucencyVolumeConfig {
        &self.config
    }

    /// Estimate total VRAM usage in bytes for the given configuration.
    pub fn vram_estimate(config: &TranslucencyVolumeConfig) -> u64 {
        let [w, h, d] = config.resolution;
        // Rgba16Float = 8 bytes per texel
        let volume_bytes = w as u64 * h as u64 * d as u64 * 8;
        // Uniform buffer
        let uniform_bytes = std::mem::size_of::<TranslucencyVolumeUniforms>() as u64;
        volume_bytes + uniform_bytes
    }

    /// Drop all GPU resources.
    pub fn destroy(&mut self) {
        if let Some(t) = self.volume_texture.take() {
            t.destroy();
        }
        if let Some(b) = self.uniform_buffer.take() {
            b.destroy();
        }
        self.volume_view = None;
        self.inject_pipeline = None;
        self.inject_bgl = None;
        self.sampler = None;
        self.initialized = false;
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn uniform_size() {
        assert_eq!(std::mem::size_of::<TranslucencyVolumeUniforms>(), 48);
    }

    #[test]
    fn config_defaults() {
        let config = TranslucencyVolumeConfig::default();
        assert_eq!(config.resolution, [64, 64, 32]);
        assert!((config.world_extent - 50.0).abs() < f32::EPSILON);
    }

    #[test]
    fn vram_estimate_under_budget() {
        let config = TranslucencyVolumeConfig::default();
        // 64×64×32 × 8 bytes = 1 MB + 48 bytes uniform
        let estimate = TranslucencyVolume::vram_estimate(&config);
        let expected_volume = 64 * 64 * 32 * 8;
        let expected_total = expected_volume + 48;
        assert_eq!(estimate, expected_total as u64);
        // Should be well under 2 MB
        assert!(estimate < 2 * 1024 * 1024, "VRAM estimate {} exceeds 2 MB", estimate);
    }

    #[test]
    fn default_is_disabled() {
        let vol = TranslucencyVolume::default();
        assert!(!vol.enabled);
        assert!(!vol.initialized);
        assert!(vol.volume_view().is_none());
        assert!(vol.sampler().is_none());
    }

    #[test]
    fn new_is_enabled() {
        let vol = TranslucencyVolume::new(TranslucencyVolumeConfig::default());
        assert!(vol.enabled);
        assert!(!vol.initialized);
    }

    #[test]
    fn custom_config() {
        let config = TranslucencyVolumeConfig {
            resolution: [128, 128, 64],
            world_extent: 100.0,
        };
        let vol = TranslucencyVolume::new(config.clone());
        assert_eq!(vol.config().resolution, [128, 128, 64]);
        assert!((vol.config().world_extent - 100.0).abs() < f32::EPSILON);

        // VRAM: 128×128×64×8 = 8 MB + 48 = 8,388,656 bytes
        let estimate = TranslucencyVolume::vram_estimate(&config);
        assert_eq!(estimate, 128 * 128 * 64 * 8 + 48);
    }

    #[test]
    fn uniform_pod_alignment() {
        // Verify Pod/Zeroable derive works (compile-time check via bytemuck).
        let u = TranslucencyVolumeUniforms {
            volume_min: [-50.0, -50.0, -50.0],
            _pad0: 0.0,
            volume_max: [50.0, 50.0, 50.0],
            _pad1: 0.0,
            resolution: [64, 64, 32],
            frame_index: 0,
        };
        let bytes = bytemuck::bytes_of(&u);
        assert_eq!(bytes.len(), 48);
    }
}
