use crate::gpu::Gpu;

pub const MAX_PLANES: usize = 8;

pub const MAX_STROKE_POINTS: usize = 10;

const STROKE_POINT_SLOTS: usize = MAX_STROKE_POINTS / 2;

#[repr(C, align(16))]
#[derive(Copy, Clone, Debug, PartialEq, bytemuck::Pod, bytemuck::Zeroable)]
pub struct ConvexInstance {
    pub rect_xywh_px: [f32; 4],
    pub fill_premul_rgba: [f32; 4],
    pub border_premul_rgba: [f32; 4],
    pub count_border_pad: [f32; 4],
    pub planes: [[f32; 4]; MAX_PLANES],
}

impl ConvexInstance {
    #[must_use]
    pub fn new(
        rect_xywh_px: [f32; 4],
        fill_premul_rgba: [f32; 4],
        border_premul_rgba: [f32; 4],
        border_width_px: f32,
        planes: &[[f32; 3]],
    ) -> Option<Self> {
        if !(1..=MAX_PLANES).contains(&planes.len()) {
            return None;
        }
        let count = u8::try_from(planes.len()).ok()?;
        let packed =
            core::array::from_fn(|i| planes.get(i).map_or([0.0; 4], |p| [p[0], p[1], p[2], 0.0]));
        Some(Self {
            rect_xywh_px,
            fill_premul_rgba,
            border_premul_rgba,
            count_border_pad: [f32::from(count), border_width_px, 0.0, 0.0],
            planes: packed,
        })
    }
}

#[repr(C, align(16))]
#[derive(Copy, Clone, Debug, PartialEq, bytemuck::Pod, bytemuck::Zeroable)]
pub struct StrokeInstance {
    pub rect_xywh_px: [f32; 4],
    pub color_premul_rgba: [f32; 4],
    pub count_half_pad: [f32; 4],
    pub points_px: [[f32; 4]; STROKE_POINT_SLOTS],
}

impl StrokeInstance {
    #[must_use]
    pub fn new(
        points_px: &[[f32; 2]],
        color_premul_rgba: [f32; 4],
        half_width_px: f32,
    ) -> Option<Self> {
        if !(2..=MAX_STROKE_POINTS).contains(&points_px.len()) {
            return None;
        }
        let count = u8::try_from(points_px.len()).ok()?;
        let pad = half_width_px.max(0.0) + 1.0;
        let (min, max) = points_px.iter().fold(
            ([f32::INFINITY; 2], [f32::NEG_INFINITY; 2]),
            |(lo, hi), p| {
                (
                    [lo[0].min(p[0]), lo[1].min(p[1])],
                    [hi[0].max(p[0]), hi[1].max(p[1])],
                )
            },
        );
        let pair = |i: usize| {
            let at = |j: usize| points_px.get(j).copied().unwrap_or([0.0; 2]);
            let (a, b) = (at(2 * i), at(2 * i + 1));
            [a[0], a[1], b[0], b[1]]
        };
        Some(Self {
            rect_xywh_px: [
                min[0] - pad,
                min[1] - pad,
                max[0] - min[0] + 2.0 * pad,
                max[1] - min[1] + 2.0 * pad,
            ],
            color_premul_rgba,
            count_half_pad: [f32::from(count), half_width_px, 0.0, 0.0],
            points_px: core::array::from_fn(pair),
        })
    }
}

#[repr(C, align(16))]
#[derive(Copy, Clone, bytemuck::Pod, bytemuck::Zeroable)]
struct VectorFrame {
    viewport_px: [f32; 2],
    pad: [f32; 2],
}

const FRAME_SIZE: u64 = core::mem::size_of::<VectorFrame>() as u64;
const INITIAL_CAP_BYTES: u64 = 256 * 64;
const VERTS_PER_INSTANCE: u32 = 6;

const CONVEX_ATTRS: [wgpu::VertexAttribute; 12] = wgpu::vertex_attr_array![
    0 => Float32x4, 1 => Float32x4, 2 => Float32x4, 3 => Float32x4,
    4 => Float32x4, 5 => Float32x4, 6 => Float32x4, 7 => Float32x4,
    8 => Float32x4, 9 => Float32x4, 10 => Float32x4, 11 => Float32x4,
];

const STROKE_ATTRS: [wgpu::VertexAttribute; 8] = wgpu::vertex_attr_array![
    0 => Float32x4, 1 => Float32x4, 2 => Float32x4, 3 => Float32x4,
    4 => Float32x4, 5 => Float32x4, 6 => Float32x4, 7 => Float32x4,
];

struct ScreenInstancePipeline {
    device: wgpu::Device,
    queue: wgpu::Queue,
    pipeline: wgpu::RenderPipeline,
    uniform_buffer: wgpu::Buffer,
    bind_group: wgpu::BindGroup,
    instances: wgpu::Buffer,
    capacity_bytes: u64,
    stride: u64,
}

impl ScreenInstancePipeline {
    fn new(
        gpu: &Gpu,
        color_format: wgpu::TextureFormat,
        label: &str,
        shader_source: &str,
        attributes: &[wgpu::VertexAttribute],
        stride: u64,
    ) -> Self {
        let device = gpu.device().clone();
        let queue = gpu.queue().clone();
        let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
            label: Some(label),
            source: wgpu::ShaderSource::Wgsl(shader_source.into()),
        });
        let bind_group_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
            label: Some(label),
            entries: &[wgpu::BindGroupLayoutEntry {
                binding: 0,
                visibility: wgpu::ShaderStages::VERTEX_FRAGMENT,
                ty: wgpu::BindingType::Buffer {
                    ty: wgpu::BufferBindingType::Uniform,
                    has_dynamic_offset: false,
                    min_binding_size: wgpu::BufferSize::new(FRAME_SIZE),
                },
                count: None,
            }],
        });
        let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
            label: Some(label),
            bind_group_layouts: &[Some(&bind_group_layout)],
            immediate_size: 0,
        });
        let pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
            label: Some(label),
            layout: Some(&pipeline_layout),
            vertex: wgpu::VertexState {
                module: &shader,
                entry_point: Some("vs"),
                compilation_options: wgpu::PipelineCompilationOptions::default(),
                buffers: &[wgpu::VertexBufferLayout {
                    array_stride: stride,
                    step_mode: wgpu::VertexStepMode::Instance,
                    attributes,
                }],
            },
            fragment: Some(wgpu::FragmentState {
                module: &shader,
                entry_point: Some("fs"),
                compilation_options: wgpu::PipelineCompilationOptions::default(),
                targets: &[Some(wgpu::ColorTargetState {
                    format: color_format,
                    blend: Some(wgpu::BlendState::PREMULTIPLIED_ALPHA_BLENDING),
                    write_mask: wgpu::ColorWrites::ALL,
                })],
            }),
            primitive: wgpu::PrimitiveState {
                topology: wgpu::PrimitiveTopology::TriangleList,
                strip_index_format: None,
                front_face: wgpu::FrontFace::Ccw,
                cull_mode: None,
                polygon_mode: wgpu::PolygonMode::Fill,
                conservative: false,
                unclipped_depth: false,
            },
            depth_stencil: None,
            multisample: wgpu::MultisampleState::default(),
            multiview_mask: None,
            cache: None,
        });
        let uniform_buffer = device.create_buffer(&wgpu::BufferDescriptor {
            label: Some(label),
            size: FRAME_SIZE,
            usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
            mapped_at_creation: false,
        });
        let bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
            label: Some(label),
            layout: &bind_group_layout,
            entries: &[wgpu::BindGroupEntry {
                binding: 0,
                resource: uniform_buffer.as_entire_binding(),
            }],
        });
        let instances = create_instance_buffer(&device, INITIAL_CAP_BYTES);
        Self {
            device,
            queue,
            pipeline,
            uniform_buffer,
            bind_group,
            instances,
            capacity_bytes: INITIAL_CAP_BYTES,
            stride,
        }
    }

    fn upload(&mut self, viewport_px: [f32; 2], instance_bytes: &[u8]) {
        let frame = VectorFrame {
            viewport_px,
            pad: [0.0, 0.0],
        };
        self.queue
            .write_buffer(&self.uniform_buffer, 0, bytemuck::bytes_of(&frame));
        if instance_bytes.is_empty() {
            return;
        }
        let needed = instance_bytes.len() as u64;
        if needed > self.capacity_bytes {
            let new_cap = needed.next_power_of_two().max(self.capacity_bytes * 2);
            self.instances = create_instance_buffer(&self.device, new_cap);
            self.capacity_bytes = new_cap;
        }
        self.queue.write_buffer(&self.instances, 0, instance_bytes);
    }

    fn draw_range(
        &self,
        encoder: &mut wgpu::CommandEncoder,
        color_view: &wgpu::TextureView,
        range: core::ops::Range<u32>,
    ) {
        if range.start >= range.end {
            return;
        }
        let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
            label: Some("bone-render:vector-pass"),
            color_attachments: &[Some(wgpu::RenderPassColorAttachment {
                view: color_view,
                resolve_target: None,
                depth_slice: None,
                ops: wgpu::Operations {
                    load: wgpu::LoadOp::Load,
                    store: wgpu::StoreOp::Store,
                },
            })],
            depth_stencil_attachment: None,
            timestamp_writes: None,
            occlusion_query_set: None,
            multiview_mask: None,
        });
        pass.set_pipeline(&self.pipeline);
        pass.set_bind_group(0, &self.bind_group, &[]);
        let start = u64::from(range.start) * self.stride;
        let end = u64::from(range.end) * self.stride;
        pass.set_vertex_buffer(0, self.instances.slice(start..end));
        pass.draw(0..VERTS_PER_INSTANCE, 0..(range.end - range.start));
    }
}

fn create_instance_buffer(device: &wgpu::Device, capacity_bytes: u64) -> wgpu::Buffer {
    device.create_buffer(&wgpu::BufferDescriptor {
        label: Some("bone-render:vector-instances"),
        size: capacity_bytes,
        usage: wgpu::BufferUsages::VERTEX | wgpu::BufferUsages::COPY_DST,
        mapped_at_creation: false,
    })
}

pub struct ConvexPolyPipeline(ScreenInstancePipeline);

impl ConvexPolyPipeline {
    #[must_use]
    pub fn new(gpu: &Gpu, color_format: wgpu::TextureFormat) -> Self {
        Self(ScreenInstancePipeline::new(
            gpu,
            color_format,
            "bone-render:convex-poly",
            include_str!("convex_poly.wgsl"),
            &CONVEX_ATTRS,
            core::mem::size_of::<ConvexInstance>() as u64,
        ))
    }

    pub fn upload(&mut self, viewport_px: [f32; 2], instances: &[ConvexInstance]) {
        self.0.upload(viewport_px, bytemuck::cast_slice(instances));
    }

    pub fn draw_range(
        &self,
        encoder: &mut wgpu::CommandEncoder,
        color_view: &wgpu::TextureView,
        range: core::ops::Range<u32>,
    ) {
        self.0.draw_range(encoder, color_view, range);
    }
}

impl core::fmt::Debug for ConvexPolyPipeline {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        f.debug_struct("ConvexPolyPipeline").finish_non_exhaustive()
    }
}

pub struct StrokePipeline(ScreenInstancePipeline);

impl StrokePipeline {
    #[must_use]
    pub fn new(gpu: &Gpu, color_format: wgpu::TextureFormat) -> Self {
        Self(ScreenInstancePipeline::new(
            gpu,
            color_format,
            "bone-render:stroke",
            include_str!("stroke.wgsl"),
            &STROKE_ATTRS,
            core::mem::size_of::<StrokeInstance>() as u64,
        ))
    }

    pub fn upload(&mut self, viewport_px: [f32; 2], instances: &[StrokeInstance]) {
        self.0.upload(viewport_px, bytemuck::cast_slice(instances));
    }

    pub fn draw_range(
        &self,
        encoder: &mut wgpu::CommandEncoder,
        color_view: &wgpu::TextureView,
        range: core::ops::Range<u32>,
    ) {
        self.0.draw_range(encoder, color_view, range);
    }
}

impl core::fmt::Debug for StrokePipeline {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        f.debug_struct("StrokePipeline").finish_non_exhaustive()
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{OffscreenContext, ViewportExtent, ViewportPx};

    fn clear_black(encoder: &mut wgpu::CommandEncoder, color: &wgpu::TextureView) {
        let _pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
            label: Some("vector-test-clear"),
            color_attachments: &[Some(wgpu::RenderPassColorAttachment {
                view: color,
                resolve_target: None,
                depth_slice: None,
                ops: wgpu::Operations {
                    load: wgpu::LoadOp::Clear(wgpu::Color::BLACK),
                    store: wgpu::StoreOp::Store,
                },
            })],
            depth_stencil_attachment: None,
            timestamp_writes: None,
            occlusion_query_set: None,
            multiview_mask: None,
        });
    }

    #[test]
    fn convex_instance_rejects_empty_and_oversized_plane_sets() {
        let unit = [1.0, 0.0, 0.0];
        let rect = [0.0, 0.0, 8.0, 8.0];
        let color = [1.0, 0.0, 0.0, 1.0];
        assert!(ConvexInstance::new(rect, color, color, 0.0, &[]).is_none());
        assert!(ConvexInstance::new(rect, color, color, 0.0, &[unit; MAX_PLANES + 1]).is_none());
        assert!(ConvexInstance::new(rect, color, color, 0.0, &[unit; MAX_PLANES]).is_some());
    }

    #[test]
    fn stroke_instance_rejects_too_few_and_too_many_points() {
        let color = [1.0, 0.0, 0.0, 1.0];
        assert!(StrokeInstance::new(&[[0.0, 0.0]], color, 1.0).is_none());
        assert!(StrokeInstance::new(&[[0.0, 0.0]; MAX_STROKE_POINTS + 1], color, 1.0).is_none());
        assert!(StrokeInstance::new(&[[0.0, 0.0]; MAX_STROKE_POINTS], color, 1.0).is_some());
    }

    #[test]
    fn stroke_instance_bounds_cover_every_point_plus_width_and_aa() {
        let Some(line) = StrokeInstance::new(&[[10.0, 20.0], [40.0, 5.0]], [0.0; 4], 3.0) else {
            panic!("two points form a stroke");
        };
        let expected = [6.0, 1.0, 38.0, 23.0];
        line.rect_xywh_px
            .iter()
            .zip(expected)
            .for_each(|(got, want)| {
                assert!(
                    (got - want).abs() < 1.0e-6,
                    "stroke rect {:?} must match {expected:?}",
                    line.rect_xywh_px,
                );
            });
    }

    #[test]
    fn a_translucent_polyline_joint_blends_once_on_the_gpu() {
        let extent = ViewportExtent::square(ViewportPx::new(64));
        let Ok(ctx) = pollster::block_on(OffscreenContext::new(extent)) else {
            return;
        };
        let mut stroke = StrokePipeline::new(ctx.gpu(), ctx.color_format());
        let Some(bend) = StrokeInstance::new(
            &[[8.0, 8.0], [8.0, 56.0], [56.0, 56.0]],
            [0.0, 0.5, 0.0, 0.5],
            3.0,
        ) else {
            panic!("three points form a stroke");
        };
        stroke.upload([64.0, 64.0], &[bend]);
        let Ok(frame) = ctx.render(|encoder, color, _pick| {
            clear_black(encoder, color);
            stroke.draw_range(encoder, color, 0..1);
        }) else {
            panic!("offscreen render failed");
        };
        let data = frame.rgba();
        let px = |x: u32, y: u32| {
            let i = ((y * 64 + x) * 4) as usize;
            [data[i], data[i + 1], data[i + 2], data[i + 3]]
        };
        let joint = px(8, 56);
        let straight = px(8, 32);
        assert!(
            joint[1].abs_diff(straight[1]) <= 8,
            "the joint must not double-blend, joint {joint:?} vs straight {straight:?}",
        );
    }

    #[test]
    fn convex_fill_and_stroke_paint_their_pixels_on_the_gpu() {
        let extent = ViewportExtent::square(ViewportPx::new(64));
        let Ok(ctx) = pollster::block_on(OffscreenContext::new(extent)) else {
            return;
        };
        let mut convex = ConvexPolyPipeline::new(ctx.gpu(), ctx.color_format());
        let mut stroke = StrokePipeline::new(ctx.gpu(), ctx.color_format());
        let Some(square) = ConvexInstance::new(
            [15.0, 15.0, 34.0, 34.0],
            [1.0, 0.0, 0.0, 1.0],
            [0.0, 0.0, 0.0, 0.0],
            0.0,
            &[
                [-1.0, 0.0, -16.0],
                [1.0, 0.0, 48.0],
                [0.0, -1.0, -16.0],
                [0.0, 1.0, 48.0],
            ],
        ) else {
            panic!("four planes are within the cap");
        };
        let Some(line) =
            StrokeInstance::new(&[[8.0, 32.0], [56.0, 32.0]], [0.0, 1.0, 0.0, 1.0], 2.0)
        else {
            panic!("two points form a stroke");
        };
        convex.upload([64.0, 64.0], &[square]);
        stroke.upload([64.0, 64.0], &[line]);
        let Ok(frame) = ctx.render(|encoder, color, _pick| {
            clear_black(encoder, color);
            convex.draw_range(encoder, color, 0..1);
            stroke.draw_range(encoder, color, 0..1);
        }) else {
            panic!("offscreen render failed");
        };
        let data = frame.rgba();
        let px = |x: u32, y: u32| {
            let i = ((y * 64 + x) * 4) as usize;
            [data[i], data[i + 1], data[i + 2], data[i + 3]]
        };
        let near = |a: [u8; 4], b: [u8; 4]| a.iter().zip(b).all(|(p, q)| p.abs_diff(q) <= 8);
        assert!(
            near(px(24, 24), [255, 0, 0, 255]),
            "convex interior must paint the fill color, got {:?}",
            px(24, 24),
        );
        assert!(
            near(px(52, 32), [0, 255, 0, 255]),
            "the stroke past the square must paint the stroke color, got {:?}",
            px(52, 32),
        );
        assert!(
            near(px(4, 4), [0, 0, 0, 255]),
            "an empty corner stays the cleared background, got {:?}",
            px(4, 4),
        );
    }
}
