use crate::camera::CameraUniforms;
use crate::postprocess::{create_blit_pipeline, create_fullscreen_quad, LowResFramebuffer};
use crate::shader::{create_environment_pipeline, create_render_pipeline};
use crate::terrain::create_terrain_render_pipeline;
use crate::texture::{DitherTextures, FlowmapTexture};
use bytemuck::{Pod, Zeroable};
use glam::Mat4;
use std::cell::RefCell;
use wesl::Wesl;

pub const MAX_SPOTLIGHTS: usize = 4;

#[repr(C)]
#[derive(Clone, Copy, Pod, Zeroable, Default)]
pub struct SpotlightRaw
{
    pub position: [f32; 3],
    pub inner_angle: f32,
    pub direction: [f32; 3],
    pub outer_angle: f32,
    pub range: f32,
    pub _padding: [f32; 7],
}

pub struct Spotlight
{
    pub position: glam::Vec3,
    pub direction: glam::Vec3,
    pub inner_angle: f32,
    pub outer_angle: f32,
    pub range: f32,
}

impl Spotlight
{
    pub fn new(
        position: glam::Vec3,
        direction: glam::Vec3,
        inner_angle: f32,
        outer_angle: f32,
        range: f32,
    ) -> Self
    {
        Self {
            position,
            direction: direction.normalize(),
            inner_angle,
            outer_angle,
            range,
        }
    }

    pub fn to_raw(&self) -> SpotlightRaw
    {
        SpotlightRaw {
            position: self.position.to_array(),
            inner_angle: self.inner_angle,
            direction: self.direction.to_array(),
            outer_angle: self.outer_angle,
            range: self.range,
            _padding: [0.0; 7],
        }
    }
}

#[repr(C)]
#[derive(Clone, Copy, Pod, Zeroable)]
struct TerrainUniforms
{
    model: [[f32; 4]; 4],
    view: [[f32; 4]; 4],
    projection: [[f32; 4]; 4],
    light_view_projection: [[f32; 4]; 4],
    camera_position: [f32; 3],
    height_scale: f32,
    player_position: [f32; 3],
    time: f32,
    shadow_bias: f32,
    spotlight_count: u32,
    _padding1: u32,
    _padding2: u32,
    spotlights: [SpotlightRaw; MAX_SPOTLIGHTS],
}

impl TerrainUniforms
{
    fn new(
        model: Mat4,
        view: Mat4,
        projection: Mat4,
        light_view_projection: Mat4,
        camera_position: glam::Vec3,
        player_position: glam::Vec3,
        height_scale: f32,
        time: f32,
        shadow_bias: f32,
        spotlights: &[Spotlight],
    ) -> Self
    {
        let mut spotlight_array = [SpotlightRaw::default(); MAX_SPOTLIGHTS];
        for (i, spotlight) in spotlights.iter().take(MAX_SPOTLIGHTS).enumerate()
        {
            spotlight_array[i] = spotlight.to_raw();
        }

        Self {
            model: model.to_cols_array_2d(),
            view: view.to_cols_array_2d(),
            projection: projection.to_cols_array_2d(),
            light_view_projection: light_view_projection.to_cols_array_2d(),
            camera_position: camera_position.to_array(),
            height_scale,
            player_position: player_position.to_array(),
            time,
            shadow_bias,
            spotlight_count: spotlights.len().min(MAX_SPOTLIGHTS) as u32,
            _padding1: 0,
            _padding2: 0,
            spotlights: spotlight_array,
        }
    }
}

#[derive(Clone, Copy)]
pub enum Pipeline
{
    Standard,
    Terrain,
    Environment,
    Wireframe,
    Snow,
}

pub struct DrawCall
{
    pub vertex_buffer: wgpu::Buffer,
    pub index_buffer: wgpu::Buffer,
    pub num_indices: u32,
    pub model: Mat4,
    pub pipeline: Pipeline,
    pub instance_buffer: Option<wgpu::Buffer>,
    pub num_instances: u32,
}

pub struct Renderer
{
    pub device: wgpu::Device,
    pub queue: wgpu::Queue,
    pub surface: wgpu::Surface<'static>,
    pub config: wgpu::SurfaceConfiguration,

    framebuffer: LowResFramebuffer,
    render_pipeline: wgpu::RenderPipeline,
    environment_pipeline: wgpu::RenderPipeline,

    uniform_buffer: wgpu::Buffer,
    bind_group: wgpu::BindGroup,

    quad_vb: wgpu::Buffer,
    quad_ib: wgpu::Buffer,
    quad_num_indices: u32,
    blit_pipeline: wgpu::RenderPipeline,
    blit_bind_group: wgpu::BindGroup,

    terrain_pipeline: Option<wgpu::RenderPipeline>,
    terrain_bind_group_layout: wgpu::BindGroupLayout,
    terrain_uniform_buffer: wgpu::Buffer,
    terrain_bind_group: Option<wgpu::BindGroup>,
    terrain_height_scale: f32,

    shadow_pipeline: Option<wgpu::RenderPipeline>,
    shadow_bind_group_layout: wgpu::BindGroupLayout,
    shadow_bind_group: Option<wgpu::BindGroup>,

    wireframe_pipeline: wgpu::RenderPipeline,
    snow_pipeline: wgpu::RenderPipeline,
    snow_bind_group_layout: wgpu::BindGroupLayout,
    snow_persistent_light_layout: wgpu::BindGroupLayout,
    snow_bind_group: wgpu::BindGroup,
    snow_persistent_light_bind_group: Option<wgpu::BindGroup>,

    pub spotlights: Vec<Spotlight>,
    pub shadow_bias: f32,

    shadow_map_texture: wgpu::Texture,
    shadow_map_view: wgpu::TextureView,
    shadow_map_sampler: wgpu::Sampler,
    shadow_map_size: u32,

    dither_textures: Option<DitherTextures>,
    flowmap_texture: Option<FlowmapTexture>,
    blue_noise_view: wgpu::TextureView,
    blue_noise_sampler: wgpu::Sampler,

    snow_light_accumulation: Option<crate::snow_light::SnowLightAccumulation>,
}

impl Renderer
{
    pub async fn new(
        window: &sdl3::video::Window,
        render_scale: u32,
    ) -> Result<Self, Box<dyn std::error::Error>>
    {
        let instance = wgpu::Instance::new(&wgpu::InstanceDescriptor {
            backends: wgpu::Backends::VULKAN,
            ..Default::default()
        });

        let surface = unsafe {
            let target = wgpu::SurfaceTargetUnsafe::from_window(window)?;
            instance.create_surface_unsafe(target)?
        };

        let adapter = instance
            .request_adapter(&wgpu::RequestAdapterOptions {
                power_preference: wgpu::PowerPreference::HighPerformance,
                compatible_surface: Some(&surface),
                force_fallback_adapter: false,
            })
            .await
            .map_err(|_| "Failed to find adapter")?;

        let (device, queue) = adapter
            .request_device(&wgpu::DeviceDescriptor::default())
            .await?;

        let size = window.size();
        let config = wgpu::SurfaceConfiguration {
            usage: wgpu::TextureUsages::RENDER_ATTACHMENT,
            format: surface.get_capabilities(&adapter).formats[0],
            width: size.0,
            height: size.1,
            present_mode: wgpu::PresentMode::Fifo,
            alpha_mode: wgpu::CompositeAlphaMode::Auto,
            view_formats: vec![],
            desired_maximum_frame_latency: 2,
        };

        surface.configure(&device, &config);

        let low_res_width = config.width / render_scale;
        let low_res_height = config.height / render_scale;

        let framebuffer =
            LowResFramebuffer::new(&device, low_res_width, low_res_height, config.format);

        let uniform_buffer = device.create_buffer(&wgpu::BufferDescriptor {
            label: Some("Uniform Buffer"),
            size: std::mem::size_of::<TerrainUniforms>() as wgpu::BufferAddress,
            usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
            mapped_at_creation: false,
        });

        let dither_textures = match DitherTextures::load_octaves(&device, &queue)
        {
            Ok(textures) =>
            {
                println!("Loaded dither textures successfully");
                Some(textures)
            }
            Err(e) =>
            {
                eprintln!(
                    "Warning: Could not load dither textures: {}. Rendering may look incorrect.",
                    e
                );
                None
            }
        };

        let flowmap_texture =
            match FlowmapTexture::load(&device, &queue, "textures/terrain_flowmap.exr")
            {
                Ok(texture) =>
                {
                    println!("Loaded terrain flowmap successfully");
                    Some(texture)
                }
                Err(e) =>
                {
                    eprintln!(
                        "Warning: Could not load terrain flowmap: {}. Path lighting will not work.",
                        e
                    );
                    None
                }
            };

        let blue_noise_data = image::open("textures/blue_noise.png")
            .expect("Failed to load blue noise texture")
            .to_luma8();
        let blue_noise_size = blue_noise_data.dimensions();

        let blue_noise_texture = device.create_texture(&wgpu::TextureDescriptor {
            label: Some("Blue Noise"),
            size: wgpu::Extent3d {
                width: blue_noise_size.0,
                height: blue_noise_size.1,
                depth_or_array_layers: 1,
            },
            mip_level_count: 1,
            sample_count: 1,
            dimension: wgpu::TextureDimension::D2,
            format: wgpu::TextureFormat::R8Unorm,
            usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
            view_formats: &[],
        });

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

        let blue_noise_view =
            blue_noise_texture.create_view(&wgpu::TextureViewDescriptor::default());
        let blue_noise_sampler = device.create_sampler(&wgpu::SamplerDescriptor {
            label: Some("Blue Noise Sampler"),
            address_mode_u: wgpu::AddressMode::Repeat,
            address_mode_v: wgpu::AddressMode::Repeat,
            mag_filter: wgpu::FilterMode::Nearest,
            min_filter: wgpu::FilterMode::Nearest,
            ..Default::default()
        });

        let shadow_map_size = 4096;
        let shadow_map_texture = device.create_texture(&wgpu::TextureDescriptor {
            label: Some("Shadow Map"),
            size: wgpu::Extent3d {
                width: shadow_map_size,
                height: shadow_map_size,
                depth_or_array_layers: 1,
            },
            mip_level_count: 1,
            sample_count: 1,
            dimension: wgpu::TextureDimension::D2,
            format: wgpu::TextureFormat::Depth32Float,
            usage: wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::TEXTURE_BINDING,
            view_formats: &[],
        });

        let shadow_map_view =
            shadow_map_texture.create_view(&wgpu::TextureViewDescriptor::default());

        let shadow_map_sampler = device.create_sampler(&wgpu::SamplerDescriptor {
            label: Some("Shadow Map Sampler"),
            address_mode_u: wgpu::AddressMode::ClampToEdge,
            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::FilterMode::Nearest,
            compare: Some(wgpu::CompareFunction::LessEqual),
            ..Default::default()
        });

        let bind_group_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
            label: Some("Bind Group Layout"),
            entries: &[
                wgpu::BindGroupLayoutEntry {
                    binding: 0,
                    visibility: wgpu::ShaderStages::VERTEX | wgpu::ShaderStages::FRAGMENT,
                    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::Depth,
                        view_dimension: wgpu::TextureViewDimension::D2,
                        multisampled: false,
                    },
                    count: None,
                },
                wgpu::BindGroupLayoutEntry {
                    binding: 2,
                    visibility: wgpu::ShaderStages::FRAGMENT,
                    ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Comparison),
                    count: None,
                },
                wgpu::BindGroupLayoutEntry {
                    binding: 3,
                    visibility: wgpu::ShaderStages::FRAGMENT,
                    ty: wgpu::BindingType::Texture {
                        sample_type: wgpu::TextureSampleType::Float { filterable: false },
                        view_dimension: wgpu::TextureViewDimension::D2Array,
                        multisampled: false,
                    },
                    count: None,
                },
                wgpu::BindGroupLayoutEntry {
                    binding: 4,
                    visibility: wgpu::ShaderStages::FRAGMENT,
                    ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::NonFiltering),
                    count: None,
                },
                wgpu::BindGroupLayoutEntry {
                    binding: 5,
                    visibility: wgpu::ShaderStages::FRAGMENT,
                    ty: wgpu::BindingType::Texture {
                        sample_type: wgpu::TextureSampleType::Float { filterable: false },
                        view_dimension: wgpu::TextureViewDimension::D2,
                        multisampled: false,
                    },
                    count: None,
                },
                wgpu::BindGroupLayoutEntry {
                    binding: 6,
                    visibility: wgpu::ShaderStages::FRAGMENT,
                    ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::NonFiltering),
                    count: None,
                },
                wgpu::BindGroupLayoutEntry {
                    binding: 7,
                    visibility: wgpu::ShaderStages::FRAGMENT,
                    ty: wgpu::BindingType::Texture {
                        sample_type: wgpu::TextureSampleType::Float { filterable: false },
                        view_dimension: wgpu::TextureViewDimension::D2,
                        multisampled: false,
                    },
                    count: None,
                },
                wgpu::BindGroupLayoutEntry {
                    binding: 8,
                    visibility: wgpu::ShaderStages::FRAGMENT,
                    ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::NonFiltering),
                    count: None,
                },
            ],
        });

        let bind_group = if let (Some(ref dither_tex), Some(ref flowmap)) =
            (&dither_textures, &flowmap_texture)
        {
            device.create_bind_group(&wgpu::BindGroupDescriptor {
                label: Some("Bind Group"),
                layout: &bind_group_layout,
                entries: &[
                    wgpu::BindGroupEntry {
                        binding: 0,
                        resource: uniform_buffer.as_entire_binding(),
                    },
                    wgpu::BindGroupEntry {
                        binding: 1,
                        resource: wgpu::BindingResource::TextureView(&shadow_map_view),
                    },
                    wgpu::BindGroupEntry {
                        binding: 2,
                        resource: wgpu::BindingResource::Sampler(&shadow_map_sampler),
                    },
                    wgpu::BindGroupEntry {
                        binding: 3,
                        resource: wgpu::BindingResource::TextureView(&dither_tex.view),
                    },
                    wgpu::BindGroupEntry {
                        binding: 4,
                        resource: wgpu::BindingResource::Sampler(&dither_tex.sampler),
                    },
                    wgpu::BindGroupEntry {
                        binding: 5,
                        resource: wgpu::BindingResource::TextureView(&flowmap.view),
                    },
                    wgpu::BindGroupEntry {
                        binding: 6,
                        resource: wgpu::BindingResource::Sampler(&flowmap.sampler),
                    },
                    wgpu::BindGroupEntry {
                        binding: 7,
                        resource: wgpu::BindingResource::TextureView(&blue_noise_view),
                    },
                    wgpu::BindGroupEntry {
                        binding: 8,
                        resource: wgpu::BindingResource::Sampler(&blue_noise_sampler),
                    },
                ],
            })
        }
        else
        {
            panic!("Cannot create renderer without dither textures and flowmap");
        };

        let render_pipeline = create_render_pipeline(&device, &config, &bind_group_layout);
        let environment_pipeline =
            create_environment_pipeline(&device, &config, &bind_group_layout);

        let (quad_vb, quad_ib, quad_num_indices) = create_fullscreen_quad(&device);

        let blit_bind_group_layout =
            device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
                label: Some("Blit Bind Group Layout"),
                entries: &[
                    wgpu::BindGroupLayoutEntry {
                        binding: 0,
                        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: 1,
                        visibility: wgpu::ShaderStages::FRAGMENT,
                        ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering),
                        count: None,
                    },
                ],
            });

        let blit_bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
            label: Some("Blit Bind Group"),
            layout: &blit_bind_group_layout,
            entries: &[
                wgpu::BindGroupEntry {
                    binding: 0,
                    resource: wgpu::BindingResource::TextureView(&framebuffer.view),
                },
                wgpu::BindGroupEntry {
                    binding: 1,
                    resource: wgpu::BindingResource::Sampler(&framebuffer.sampler),
                },
            ],
        });

        let blit_pipeline = create_blit_pipeline(&device, config.format, &blit_bind_group_layout);

        let shadow_bind_group_layout =
            device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
                label: Some("Shadow Bind Group Layout"),
                entries: &[wgpu::BindGroupLayoutEntry {
                    binding: 0,
                    visibility: wgpu::ShaderStages::VERTEX | wgpu::ShaderStages::FRAGMENT,
                    ty: wgpu::BindingType::Buffer {
                        ty: wgpu::BufferBindingType::Uniform,
                        has_dynamic_offset: false,
                        min_binding_size: None,
                    },
                    count: None,
                }],
            });

        let wireframe_pipeline =
            create_wireframe_pipeline(&device, config.format, &bind_group_layout);

        let snow_persistent_light_layout =
            crate::snow_light::SnowLightAccumulation::create_bind_group_layout(&device);

        let snow_pipeline = create_snow_pipeline(
            &device,
            config.format,
            &bind_group_layout,
            &snow_persistent_light_layout,
        );

        let snow_bind_group_layout = bind_group_layout.clone();

        Ok(Self {
            device,
            queue,
            surface,
            config,
            framebuffer,
            render_pipeline,
            environment_pipeline,
            uniform_buffer: uniform_buffer.clone(),
            bind_group: bind_group.clone(),
            quad_vb,
            quad_ib,
            quad_num_indices,
            blit_pipeline,
            blit_bind_group,
            terrain_pipeline: None,
            terrain_bind_group_layout: bind_group_layout.clone(),
            terrain_uniform_buffer: uniform_buffer,
            terrain_bind_group: Some(bind_group.clone()),
            terrain_height_scale: 10.0,
            shadow_pipeline: None,
            shadow_bind_group_layout,
            shadow_bind_group: None,
            wireframe_pipeline,
            snow_pipeline,
            snow_bind_group_layout,
            snow_persistent_light_layout,
            snow_bind_group: bind_group,
            snow_persistent_light_bind_group: None,
            spotlights: vec![Spotlight::new(
                glam::Vec3::new(0.0, 50.0, 0.0),
                glam::Vec3::new(-0.5, -1.0, 1.0).normalize(),
                0.4,
                1.0,
                100.0,
            )],
            shadow_bias: 0.005,
            shadow_map_texture,
            shadow_map_view,
            shadow_map_sampler,
            shadow_map_size,
            dither_textures,
            flowmap_texture,
            blue_noise_view,
            blue_noise_sampler,
            snow_light_accumulation: None,
        })
    }

    pub fn render(
        &mut self,
        view: &glam::Mat4,
        projection: &glam::Mat4,
        camera_position: glam::Vec3,
        player_position: glam::Vec3,
        draw_calls: &[DrawCall],
        time: f32,
        delta_time: f32,
    )
    {
        let light_view_projection = self.calculate_light_view_projection();

        if let Some(ref mut snow_light_accum) = self.snow_light_accumulation
        {
            let mut encoder = self
                .device
                .create_command_encoder(&wgpu::CommandEncoderDescriptor {
                    label: Some("Snow Light Accumulation Encoder"),
                });

            snow_light_accum.render(
                &mut encoder,
                &self.queue,
                &self.spotlights,
                delta_time,
                &light_view_projection,
                self.shadow_bias,
                self.terrain_height_scale,
            );

            self.queue.submit(std::iter::once(encoder.finish()));

            if self.snow_persistent_light_bind_group.is_none()
            {
                let bind_group = snow_light_accum
                    .create_read_bind_group(&self.device, &self.snow_persistent_light_layout);
                self.snow_persistent_light_bind_group = Some(bind_group);
            }
        }

        self.render_shadow_pass(draw_calls, light_view_projection, player_position, time);

        for (i, draw_call) in draw_calls.iter().enumerate()
        {
            match draw_call.pipeline
            {
                Pipeline::Standard | Pipeline::Wireframe =>
                {
                    let light_dir = if self.spotlights.is_empty()
                    {
                        glam::Vec3::new(0.0, -1.0, 0.0)
                    }
                    else
                    {
                        self.spotlights[0].direction
                    };
                    let uniforms =
                        CameraUniforms::new(draw_call.model, *view, *projection, light_dir);
                    self.queue.write_buffer(
                        &self.uniform_buffer,
                        0,
                        bytemuck::cast_slice(&[uniforms]),
                    );
                }
                Pipeline::Snow | Pipeline::Terrain | Pipeline::Environment =>
                {
                    let uniforms = TerrainUniforms::new(
                        draw_call.model,
                        *view,
                        *projection,
                        light_view_projection,
                        camera_position,
                        player_position,
                        self.terrain_height_scale,
                        time,
                        self.shadow_bias,
                        &self.spotlights,
                    );
                    self.queue.write_buffer(
                        &self.terrain_uniform_buffer,
                        0,
                        bytemuck::cast_slice(&[uniforms]),
                    );
                }
            }

            let mut encoder = self
                .device
                .create_command_encoder(&wgpu::CommandEncoderDescriptor {
                    label: Some("Render Encoder"),
                });

            {
                let mut render_pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
                    label: Some("3D Render Pass"),
                    color_attachments: &[Some(wgpu::RenderPassColorAttachment {
                        view: &self.framebuffer.view,
                        resolve_target: None,
                        ops: wgpu::Operations {
                            load: if i == 0
                            {
                                wgpu::LoadOp::Clear(wgpu::Color {
                                    r: 0.2,
                                    g: 0.2,
                                    b: 0.2,
                                    a: 1.0,
                                })
                            }
                            else
                            {
                                wgpu::LoadOp::Load
                            },
                            store: wgpu::StoreOp::Store,
                        },
                        depth_slice: None,
                    })],
                    depth_stencil_attachment: Some(wgpu::RenderPassDepthStencilAttachment {
                        view: &self.framebuffer.depth_view,
                        depth_ops: Some(wgpu::Operations {
                            load: if i == 0
                            {
                                wgpu::LoadOp::Clear(1.0)
                            }
                            else
                            {
                                wgpu::LoadOp::Load
                            },
                            store: wgpu::StoreOp::Store,
                        }),
                        stencil_ops: None,
                    }),
                    timestamp_writes: None,
                    occlusion_query_set: None,
                });

                let pipeline = match draw_call.pipeline
                {
                    Pipeline::Standard => &self.render_pipeline,
                    Pipeline::Terrain => &self
                        .terrain_pipeline
                        .as_ref()
                        .expect("terrain_data_missing"),
                    Pipeline::Environment => &self.environment_pipeline,
                    Pipeline::Wireframe => &self.wireframe_pipeline,
                    Pipeline::Snow => &self.snow_pipeline,
                };
                render_pass.set_pipeline(pipeline);

                match draw_call.pipeline
                {
                    Pipeline::Standard | Pipeline::Wireframe =>
                    {
                        render_pass.set_bind_group(0, &self.bind_group, &[]);
                    }
                    Pipeline::Terrain | Pipeline::Environment =>
                    {
                        let bind_group = self
                            .terrain_bind_group
                            .as_ref()
                            .expect("terrain_data_missing");
                        render_pass.set_bind_group(0, bind_group, &[]);
                    }
                    Pipeline::Snow =>
                    {
                        render_pass.set_bind_group(0, &self.snow_bind_group, &[]);
                        if let Some(ref persistent_light_bind_group) =
                            self.snow_persistent_light_bind_group
                        {
                            render_pass.set_bind_group(1, persistent_light_bind_group, &[]);
                        }
                    }
                }

                render_pass.set_vertex_buffer(0, draw_call.vertex_buffer.slice(..));

                if let Some(ref instance_buffer) = draw_call.instance_buffer
                {
                    render_pass.set_vertex_buffer(1, instance_buffer.slice(..));
                }

                render_pass
                    .set_index_buffer(draw_call.index_buffer.slice(..), wgpu::IndexFormat::Uint32);
                render_pass.draw_indexed(0..draw_call.num_indices, 0, 0..draw_call.num_instances);
            }

            self.queue.submit(std::iter::once(encoder.finish()));
        }

        let frame = match self.surface.get_current_texture()
        {
            Ok(frame) => frame,
            Err(_) =>
            {
                self.surface.configure(&self.device, &self.config);
                self.surface
                    .get_current_texture()
                    .expect("Failed to acquire next surface texture")
            }
        };

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

        let mut blit_encoder =
            self.device
                .create_command_encoder(&wgpu::CommandEncoderDescriptor {
                    label: Some("Blit Encoder"),
                });

        {
            let mut blit_pass = blit_encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
                label: Some("Blit Pass"),
                color_attachments: &[Some(wgpu::RenderPassColorAttachment {
                    view: &screen_view,
                    resolve_target: None,
                    ops: wgpu::Operations {
                        load: wgpu::LoadOp::Clear(wgpu::Color::BLACK),
                        store: wgpu::StoreOp::Store,
                    },
                    depth_slice: None,
                })],
                depth_stencil_attachment: None,
                timestamp_writes: None,
                occlusion_query_set: None,
            });

            blit_pass.set_pipeline(&self.blit_pipeline);
            blit_pass.set_bind_group(0, &self.blit_bind_group, &[]);
            blit_pass.set_vertex_buffer(0, self.quad_vb.slice(..));
            blit_pass.set_index_buffer(self.quad_ib.slice(..), wgpu::IndexFormat::Uint16);
            blit_pass.draw_indexed(0..self.quad_num_indices, 0, 0..1);
        }

        self.queue.submit(std::iter::once(blit_encoder.finish()));
        frame.present();
    }

    pub fn render_scale(&self) -> (u32, u32)
    {
        (
            self.config.width / self.framebuffer.width,
            self.config.height / self.framebuffer.height,
        )
    }

    pub fn set_terrain_data(&mut self)
    {
        let dither_textures = self
            .dither_textures
            .as_ref()
            .expect("Dither textures should be loaded during initialization");

        let flowmap_texture = self
            .flowmap_texture
            .as_ref()
            .expect("Flowmap texture should be loaded during initialization");

        let terrain_bind_group = self.device.create_bind_group(&wgpu::BindGroupDescriptor {
            label: Some("Terrain Bind Group"),
            layout: &self.terrain_bind_group_layout,
            entries: &[
                wgpu::BindGroupEntry {
                    binding: 0,
                    resource: self.terrain_uniform_buffer.as_entire_binding(),
                },
                wgpu::BindGroupEntry {
                    binding: 1,
                    resource: wgpu::BindingResource::TextureView(&self.shadow_map_view),
                },
                wgpu::BindGroupEntry {
                    binding: 2,
                    resource: wgpu::BindingResource::Sampler(&self.shadow_map_sampler),
                },
                wgpu::BindGroupEntry {
                    binding: 3,
                    resource: wgpu::BindingResource::TextureView(&dither_textures.view),
                },
                wgpu::BindGroupEntry {
                    binding: 4,
                    resource: wgpu::BindingResource::Sampler(&dither_textures.sampler),
                },
                wgpu::BindGroupEntry {
                    binding: 5,
                    resource: wgpu::BindingResource::TextureView(&flowmap_texture.view),
                },
                wgpu::BindGroupEntry {
                    binding: 6,
                    resource: wgpu::BindingResource::Sampler(&flowmap_texture.sampler),
                },
                wgpu::BindGroupEntry {
                    binding: 7,
                    resource: wgpu::BindingResource::TextureView(&self.blue_noise_view),
                },
                wgpu::BindGroupEntry {
                    binding: 8,
                    resource: wgpu::BindingResource::Sampler(&self.blue_noise_sampler),
                },
            ],
        });

        let shadow_bind_group = self.device.create_bind_group(&wgpu::BindGroupDescriptor {
            label: Some("Shadow Bind Group"),
            layout: &self.shadow_bind_group_layout,
            entries: &[wgpu::BindGroupEntry {
                binding: 0,
                resource: self.terrain_uniform_buffer.as_entire_binding(),
            }],
        });

        let terrain_pipeline = create_terrain_render_pipeline(
            &self.device,
            &self.config,
            &self.terrain_bind_group_layout,
        );

        let shadow_pipeline = create_shadow_pipeline(&self.device, &self.shadow_bind_group_layout);

        self.terrain_bind_group = Some(terrain_bind_group);
        self.terrain_pipeline = Some(terrain_pipeline);
        self.shadow_bind_group = Some(shadow_bind_group);
        self.shadow_pipeline = Some(shadow_pipeline);
        self.terrain_height_scale = 1.0;
    }

    pub fn init_snow_light_accumulation(&mut self, terrain_min: glam::Vec2, terrain_max: glam::Vec2)
    {
        let snow_light_accumulation = crate::snow_light::SnowLightAccumulation::new(
            &self.device,
            terrain_min,
            terrain_max,
            512,
        );

        self.snow_light_accumulation = Some(snow_light_accumulation);
    }

    pub fn set_snow_depth(&mut self, snow_depth_view: &wgpu::TextureView)
    {
        println!("set_snow_depth() called");
        if let Some(ref mut snow_light_accum) = self.snow_light_accumulation
        {
            println!("Snow light accumulation exists, setting up bind groups");
            let snow_depth_sampler = self.device.create_sampler(&wgpu::SamplerDescriptor {
                label: Some("Snow Depth Sampler"),
                address_mode_u: wgpu::AddressMode::ClampToEdge,
                address_mode_v: wgpu::AddressMode::ClampToEdge,
                mag_filter: wgpu::FilterMode::Nearest,
                min_filter: wgpu::FilterMode::Nearest,
                ..Default::default()
            });

            match crate::texture::HeightmapTexture::load(
                &self.device,
                &self.queue,
                "textures/terrain_heightmap.exr",
            )
            {
                Ok(heightmap) =>
                {
                    snow_light_accum.set_heightmap(
                        &self.device,
                        &heightmap.view,
                        &heightmap.sampler,
                        &self.shadow_map_view,
                        &self.shadow_map_sampler,
                        snow_depth_view,
                        &snow_depth_sampler,
                    );

                    let bind_group = snow_light_accum
                        .create_read_bind_group(&self.device, &self.snow_persistent_light_layout);
                    self.snow_persistent_light_bind_group = Some(bind_group);
                }
                Err(e) =>
                {
                    eprintln!("Failed to load heightmap for snow depth setup: {}", e);
                }
            }
        }
    }

    pub fn get_device(&self) -> &wgpu::Device
    {
        &self.device
    }

    pub fn aspect_ratio(&self) -> f32
    {
        self.config.width as f32 / self.config.height as f32
    }

    fn render_shadow_pass(
        &mut self,
        draw_calls: &[DrawCall],
        light_view_projection: Mat4,
        player_position: glam::Vec3,
        time: f32,
    )
    {
        let uniforms = TerrainUniforms::new(
            Mat4::IDENTITY,
            Mat4::IDENTITY,
            light_view_projection,
            light_view_projection,
            glam::Vec3::ZERO,
            player_position,
            self.terrain_height_scale,
            time,
            self.shadow_bias,
            &self.spotlights,
        );
        self.queue.write_buffer(
            &self.terrain_uniform_buffer,
            0,
            bytemuck::cast_slice(&[uniforms]),
        );

        let mut encoder = self
            .device
            .create_command_encoder(&wgpu::CommandEncoderDescriptor {
                label: Some("Shadow Pass Encoder"),
            });

        {
            let mut shadow_pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
                label: Some("Shadow Pass"),
                color_attachments: &[],
                depth_stencil_attachment: Some(wgpu::RenderPassDepthStencilAttachment {
                    view: &self.shadow_map_view,
                    depth_ops: Some(wgpu::Operations {
                        load: wgpu::LoadOp::Clear(1.0),
                        store: wgpu::StoreOp::Store,
                    }),
                    stencil_ops: None,
                }),
                timestamp_writes: None,
                occlusion_query_set: None,
            });

            shadow_pass.set_pipeline(
                self.shadow_pipeline
                    .as_ref()
                    .expect("shadow pipeline missing"),
            );
            shadow_pass.set_bind_group(
                0,
                self.shadow_bind_group
                    .as_ref()
                    .expect("shadow bind group missing"),
                &[],
            );

            for draw_call in draw_calls.iter()
            {
                if !matches!(
                    draw_call.pipeline,
                    Pipeline::Terrain | Pipeline::Standard | Pipeline::Environment | Pipeline::Snow
                )
                {
                    continue;
                }

                shadow_pass.set_vertex_buffer(0, draw_call.vertex_buffer.slice(..));

                if let Some(ref instance_buffer) = draw_call.instance_buffer
                {
                    shadow_pass.set_vertex_buffer(1, instance_buffer.slice(..));
                }

                shadow_pass
                    .set_index_buffer(draw_call.index_buffer.slice(..), wgpu::IndexFormat::Uint32);
                shadow_pass.draw_indexed(0..draw_call.num_indices, 0, 0..draw_call.num_instances);
            }
        }

        self.queue.submit(std::iter::once(encoder.finish()));
    }

    fn calculate_light_view_projection(&self) -> Mat4
    {
        if self.spotlights.is_empty()
        {
            return Mat4::IDENTITY;
        }

        let spotlight = &self.spotlights[0];
        let light_position = spotlight.position;
        let light_target = spotlight.position + spotlight.direction;

        let up_vector = if spotlight.direction.y.abs() > 0.99
        {
            glam::Vec3::Z
        }
        else
        {
            glam::Vec3::Y
        };

        let light_view = Mat4::look_at_rh(light_position, light_target, up_vector);

        let fov = spotlight.outer_angle * 2.0;
        let near = 0.1;
        let far = 150.0;
        let light_projection = Mat4::perspective_rh(fov, 1.0, near, far);

        light_projection * light_view
    }

    fn calculate_light_view_projection_ortho(&self) -> Mat4
    {
        let light_dir = self.spotlights[0].direction;
        let shadow_focus_point = glam::Vec3::ZERO;
        let shadow_ortho_size = 600.0;
        let shadow_distance = 1000.0;
        let light_position = shadow_focus_point - light_dir * shadow_distance;

        let up_vector = if light_dir.y.abs() > 0.99
        {
            glam::Vec3::Z
        }
        else
        {
            glam::Vec3::Y
        };

        let light_view = Mat4::look_at_rh(light_position, shadow_focus_point, up_vector);

        let far_plane = shadow_distance * 2.0 + 50.0;
        let light_projection = Mat4::orthographic_rh(
            -shadow_ortho_size,
            shadow_ortho_size,
            -shadow_ortho_size,
            shadow_ortho_size,
            0.1,
            far_plane,
        );

        println!("Shadow Frustum - Size: {:.1}×{:.1}, Coverage: {:.1}×{:.1}, Depth: 0.1-{:.1}, Focus: {:?}, Light: {:?}",
            shadow_ortho_size * 2.0, shadow_ortho_size * 2.0,
            shadow_ortho_size, shadow_ortho_size,
            far_plane, shadow_focus_point, light_position);

        light_projection * light_view
    }
}

thread_local! {
    static GLOBAL_RENDERER: RefCell<Option<Renderer>> = RefCell::new(None);
}

pub fn init(renderer: Renderer)
{
    GLOBAL_RENDERER.with(|r| *r.borrow_mut() = Some(renderer));
}

pub fn with_device<F, R>(f: F) -> R
where
    F: FnOnce(&wgpu::Device) -> R,
{
    GLOBAL_RENDERER.with(|r| {
        let renderer = r.borrow();
        let renderer = renderer.as_ref().expect("Renderer not set");
        f(&renderer.device)
    })
}

pub fn with_queue<F, R>(f: F) -> R
where
    F: FnOnce(&wgpu::Queue) -> R,
{
    GLOBAL_RENDERER.with(|r| {
        let renderer = r.borrow();
        let renderer = renderer.as_ref().expect("Renderer not set");
        f(&renderer.queue)
    })
}

pub fn set_terrain_data()
{
    GLOBAL_RENDERER.with(|r| {
        let mut renderer = r.borrow_mut();
        let renderer = renderer.as_mut().expect("Renderer not set");
        renderer.set_terrain_data();
    });
}

pub fn init_snow_light_accumulation(terrain_min: glam::Vec2, terrain_max: glam::Vec2)
{
    GLOBAL_RENDERER.with(|r| {
        let mut renderer = r.borrow_mut();
        let renderer = renderer.as_mut().expect("Renderer not set");
        renderer.init_snow_light_accumulation(terrain_min, terrain_max);
    });
}

pub fn set_snow_depth(snow_depth_view: &wgpu::TextureView)
{
    GLOBAL_RENDERER.with(|r| {
        let mut renderer = r.borrow_mut();
        let renderer = renderer.as_mut().expect("Renderer not set");
        renderer.set_snow_depth(snow_depth_view);
    });
}

pub fn aspect_ratio() -> f32
{
    GLOBAL_RENDERER.with(|r| {
        let renderer = r.borrow();
        let renderer = renderer.as_ref().expect("Renderer not set");
        renderer.aspect_ratio()
    })
}

pub fn render(
    view: &glam::Mat4,
    projection: &glam::Mat4,
    camera_position: glam::Vec3,
    player_position: glam::Vec3,
    draw_calls: &[DrawCall],
    time: f32,
    delta_time: f32,
)
{
    GLOBAL_RENDERER.with(|r| {
        let mut renderer = r.borrow_mut();
        let renderer = renderer.as_mut().expect("Renderer not set");
        renderer.render(
            view,
            projection,
            camera_position,
            player_position,
            draw_calls,
            time,
            delta_time,
        );
    });
}

pub fn set_shadow_bias(bias: f32)
{
    GLOBAL_RENDERER.with(|r| {
        let mut renderer = r.borrow_mut();
        let renderer = renderer.as_mut().expect("Renderer not set");
        renderer.shadow_bias = bias;
    });
}

pub fn update_spotlights(spotlights: Vec<Spotlight>)
{
    GLOBAL_RENDERER.with(|r| {
        let mut renderer = r.borrow_mut();
        let renderer = renderer.as_mut().expect("Renderer not set");
        renderer.spotlights = spotlights;
    });
}

fn create_shadow_pipeline(
    device: &wgpu::Device,
    bind_group_layout: &wgpu::BindGroupLayout,
) -> wgpu::RenderPipeline
{
    let compiler = Wesl::new("src/shaders");
    let shader_source = compiler
        .compile(&"package::shadow".parse().unwrap())
        .inspect_err(|e| eprintln!("WESL error: {e}"))
        .unwrap()
        .to_string();

    let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
        label: Some("Shadow Shader"),
        source: wgpu::ShaderSource::Wgsl(shader_source.into()),
    });

    let render_pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
        label: Some("Shadow Pipeline Layout"),
        bind_group_layouts: &[bind_group_layout],
        push_constant_ranges: &[],
    });

    device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
        label: Some("Shadow Pipeline"),
        layout: Some(&render_pipeline_layout),
        vertex: wgpu::VertexState {
            module: &shader,
            entry_point: Some("vs_main"),
            buffers: &[
                crate::mesh::Vertex::desc(),
                crate::mesh::InstanceRaw::desc(),
            ],
            compilation_options: Default::default(),
        },
        fragment: None,
        primitive: wgpu::PrimitiveState {
            topology: wgpu::PrimitiveTopology::TriangleList,
            strip_index_format: None,
            front_face: wgpu::FrontFace::Ccw,
            cull_mode: Some(wgpu::Face::Back),
            polygon_mode: wgpu::PolygonMode::Fill,
            unclipped_depth: false,
            conservative: false,
        },
        depth_stencil: Some(wgpu::DepthStencilState {
            format: wgpu::TextureFormat::Depth32Float,
            depth_write_enabled: true,
            depth_compare: wgpu::CompareFunction::Less,
            stencil: wgpu::StencilState::default(),
            bias: wgpu::DepthBiasState::default(),
        }),
        multisample: wgpu::MultisampleState {
            count: 1,
            mask: !0,
            alpha_to_coverage_enabled: false,
        },
        multiview: None,
        cache: None,
    })
}

fn create_wireframe_pipeline(
    device: &wgpu::Device,
    format: wgpu::TextureFormat,
    bind_group_layout: &wgpu::BindGroupLayout,
) -> wgpu::RenderPipeline
{
    let compiler = Wesl::new("src/shaders");
    let shader_source = compiler
        .compile(&"package::standard".parse().unwrap())
        .inspect_err(|e| eprintln!("WESL error: {e}"))
        .unwrap()
        .to_string();

    let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
        label: Some("Wireframe Shader"),
        source: wgpu::ShaderSource::Wgsl(shader_source.into()),
    });

    let render_pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
        label: Some("Wireframe Pipeline Layout"),
        bind_group_layouts: &[bind_group_layout],
        push_constant_ranges: &[],
    });

    device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
        label: Some("Wireframe Pipeline"),
        layout: Some(&render_pipeline_layout),
        vertex: wgpu::VertexState {
            module: &shader,
            entry_point: Some("vs_main"),
            buffers: &[
                crate::mesh::Vertex::desc(),
                crate::mesh::InstanceRaw::desc(),
            ],
            compilation_options: Default::default(),
        },
        fragment: Some(wgpu::FragmentState {
            module: &shader,
            entry_point: Some("fs_main"),
            targets: &[Some(wgpu::ColorTargetState {
                format,
                blend: Some(wgpu::BlendState::REPLACE),
                write_mask: wgpu::ColorWrites::ALL,
            })],
            compilation_options: Default::default(),
        }),
        primitive: wgpu::PrimitiveState {
            topology: wgpu::PrimitiveTopology::LineList,
            strip_index_format: None,
            front_face: wgpu::FrontFace::Ccw,
            cull_mode: None,
            polygon_mode: wgpu::PolygonMode::Fill,
            unclipped_depth: false,
            conservative: false,
        },
        depth_stencil: Some(wgpu::DepthStencilState {
            format: wgpu::TextureFormat::Depth32Float,
            depth_write_enabled: true,
            depth_compare: wgpu::CompareFunction::Less,
            stencil: wgpu::StencilState::default(),
            bias: wgpu::DepthBiasState::default(),
        }),
        multisample: wgpu::MultisampleState {
            count: 1,
            mask: !0,
            alpha_to_coverage_enabled: false,
        },
        multiview: None,
        cache: None,
    })
}

fn create_snow_pipeline(
    device: &wgpu::Device,
    format: wgpu::TextureFormat,
    bind_group_layout_0: &wgpu::BindGroupLayout,
    bind_group_layout_1: &wgpu::BindGroupLayout,
) -> wgpu::RenderPipeline
{
    let compiler = Wesl::new("src/shaders");
    let shader_source = compiler
        .compile(&"package::snow".parse().unwrap())
        .inspect_err(|e| eprintln!("WESL error: {e}"))
        .unwrap()
        .to_string();

    let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
        label: Some("Snow Shader"),
        source: wgpu::ShaderSource::Wgsl(shader_source.into()),
    });

    let render_pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
        label: Some("Snow Pipeline Layout"),
        bind_group_layouts: &[bind_group_layout_0, bind_group_layout_1],
        push_constant_ranges: &[],
    });

    device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
        label: Some("Snow Pipeline"),
        layout: Some(&render_pipeline_layout),
        vertex: wgpu::VertexState {
            module: &shader,
            entry_point: Some("vs_main"),
            buffers: &[
                crate::mesh::Vertex::desc(),
                crate::mesh::InstanceRaw::desc(),
            ],
            compilation_options: Default::default(),
        },
        fragment: Some(wgpu::FragmentState {
            module: &shader,
            entry_point: Some("fs_main"),
            targets: &[Some(wgpu::ColorTargetState {
                format,
                blend: Some(wgpu::BlendState::REPLACE),
                write_mask: wgpu::ColorWrites::ALL,
            })],
            compilation_options: Default::default(),
        }),
        primitive: wgpu::PrimitiveState {
            topology: wgpu::PrimitiveTopology::TriangleList,
            strip_index_format: None,
            front_face: wgpu::FrontFace::Ccw,
            cull_mode: Some(wgpu::Face::Back),
            polygon_mode: wgpu::PolygonMode::Fill,
            unclipped_depth: false,
            conservative: false,
        },
        depth_stencil: Some(wgpu::DepthStencilState {
            format: wgpu::TextureFormat::Depth32Float,
            depth_write_enabled: true,
            depth_compare: wgpu::CompareFunction::Less,
            stencil: wgpu::StencilState::default(),
            bias: wgpu::DepthBiasState {
                constant: -1,
                slope_scale: -1.0,
                clamp: 0.0,
            },
        }),
        multisample: wgpu::MultisampleState {
            count: 1,
            mask: !0,
            alpha_to_coverage_enabled: false,
        },
        multiview: None,
        cache: None,
    })
}
