//! Graphics settings resources.

use serde::{Deserialize, Serialize};

/// Debug visualization mode for PBR rendering components.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
pub enum PbrDebugMode {
    #[default]
    None,
    BaseColor,
    Normal,
    Metallic,
    Roughness,
    Occlusion,
    Emissive,
    F,
    G,
    D,
    Diffuse,
    Specular,
}

impl PbrDebugMode {
    pub const ALL: &'static [PbrDebugMode] = &[
        PbrDebugMode::None,
        PbrDebugMode::BaseColor,
        PbrDebugMode::Normal,
        PbrDebugMode::Metallic,
        PbrDebugMode::Roughness,
        PbrDebugMode::Occlusion,
        PbrDebugMode::Emissive,
        PbrDebugMode::F,
        PbrDebugMode::G,
        PbrDebugMode::D,
        PbrDebugMode::Diffuse,
        PbrDebugMode::Specular,
    ];

    pub fn name(&self) -> &'static str {
        match self {
            PbrDebugMode::None => "None",
            PbrDebugMode::BaseColor => "Base Color",
            PbrDebugMode::Normal => "Normal",
            PbrDebugMode::Metallic => "Metallic",
            PbrDebugMode::Roughness => "Roughness",
            PbrDebugMode::Occlusion => "Occlusion",
            PbrDebugMode::Emissive => "Emissive",
            PbrDebugMode::F => "Fresnel (F)",
            PbrDebugMode::G => "Geometry (G)",
            PbrDebugMode::D => "Distribution (D)",
            PbrDebugMode::Diffuse => "Diffuse",
            PbrDebugMode::Specular => "Specular",
        }
    }

    pub fn as_u32(&self) -> u32 {
        match self {
            PbrDebugMode::None => 0,
            PbrDebugMode::BaseColor => 1,
            PbrDebugMode::Normal => 2,
            PbrDebugMode::Metallic => 3,
            PbrDebugMode::Roughness => 4,
            PbrDebugMode::Occlusion => 5,
            PbrDebugMode::Emissive => 6,
            PbrDebugMode::F => 7,
            PbrDebugMode::G => 8,
            PbrDebugMode::D => 9,
            PbrDebugMode::Diffuse => 10,
            PbrDebugMode::Specular => 11,
        }
    }
}

/// Quality level for depth of field effect.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
pub enum DepthOfFieldQuality {
    /// 8 samples per pixel.
    Low,
    /// 16 samples per pixel.
    #[default]
    Medium,
    /// 32 samples per pixel.
    High,
}

impl DepthOfFieldQuality {
    pub const ALL: &'static [DepthOfFieldQuality] = &[
        DepthOfFieldQuality::Low,
        DepthOfFieldQuality::Medium,
        DepthOfFieldQuality::High,
    ];

    pub fn name(&self) -> &'static str {
        match self {
            DepthOfFieldQuality::Low => "Low",
            DepthOfFieldQuality::Medium => "Medium",
            DepthOfFieldQuality::High => "High",
        }
    }

    pub fn sample_count(&self) -> u32 {
        match self {
            DepthOfFieldQuality::Low => 8,
            DepthOfFieldQuality::Medium => 16,
            DepthOfFieldQuality::High => 32,
        }
    }
}

/// Depth of field post-processing settings.
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
pub struct DepthOfField {
    /// Whether DOF is active.
    pub enabled: bool,
    /// Distance to the focal plane in world units.
    pub focus_distance: f32,
    /// Range around focus distance that remains sharp.
    pub focus_range: f32,
    /// Maximum blur radius in pixels.
    pub max_blur_radius: f32,
    /// Brightness threshold for bokeh highlights.
    pub bokeh_threshold: f32,
    /// Intensity multiplier for bokeh highlights.
    pub bokeh_intensity: f32,
    /// Sample count quality level.
    pub quality: DepthOfFieldQuality,
    /// Debug visualization of circle of confusion.
    pub visualize_coc: bool,
    /// Enable tilt-shift miniature effect.
    pub tilt_shift_enabled: bool,
    /// Angle of the tilt-shift band in radians.
    pub tilt_shift_angle: f32,
    /// Vertical position of the sharp band center (-1 to 1).
    pub tilt_shift_center: f32,
    /// Blur strength outside the sharp band.
    pub tilt_shift_blur_amount: f32,
    /// Debug visualization of tilt-shift mask.
    pub visualize_tilt_shift: bool,
}

impl Default for DepthOfField {
    fn default() -> Self {
        Self {
            enabled: false,
            focus_distance: 10.0,
            focus_range: 5.0,
            max_blur_radius: 8.0,
            bokeh_threshold: 0.8,
            bokeh_intensity: 1.0,
            quality: DepthOfFieldQuality::Medium,
            visualize_coc: false,
            tilt_shift_enabled: false,
            tilt_shift_angle: 0.0,
            tilt_shift_center: 0.0,
            tilt_shift_blur_amount: 1.0,
            visualize_tilt_shift: false,
        }
    }
}

impl DepthOfField {
    /// Preset for close-up portraits with strong background blur.
    pub fn portrait() -> Self {
        Self {
            enabled: true,
            focus_distance: 3.0,
            focus_range: 1.5,
            max_blur_radius: 12.0,
            bokeh_threshold: 0.6,
            bokeh_intensity: 1.2,
            quality: DepthOfFieldQuality::High,
            visualize_coc: false,
            tilt_shift_enabled: false,
            tilt_shift_angle: 0.0,
            tilt_shift_center: 0.0,
            tilt_shift_blur_amount: 1.0,
            visualize_tilt_shift: false,
        }
    }

    /// Preset for cinematic medium-distance focus.
    pub fn cinematic() -> Self {
        Self {
            enabled: true,
            focus_distance: 8.0,
            focus_range: 4.0,
            max_blur_radius: 10.0,
            bokeh_threshold: 0.7,
            bokeh_intensity: 1.0,
            quality: DepthOfFieldQuality::Medium,
            visualize_coc: false,
            tilt_shift_enabled: false,
            tilt_shift_angle: 0.0,
            tilt_shift_center: 0.0,
            tilt_shift_blur_amount: 1.0,
            visualize_tilt_shift: false,
        }
    }

    pub fn macro_shot() -> Self {
        Self {
            enabled: true,
            focus_distance: 0.5,
            focus_range: 0.2,
            max_blur_radius: 16.0,
            bokeh_threshold: 0.5,
            bokeh_intensity: 1.5,
            quality: DepthOfFieldQuality::High,
            visualize_coc: false,
            tilt_shift_enabled: false,
            tilt_shift_angle: 0.0,
            tilt_shift_center: 0.0,
            tilt_shift_blur_amount: 1.0,
            visualize_tilt_shift: false,
        }
    }

    pub fn landscape() -> Self {
        Self {
            enabled: true,
            focus_distance: 50.0,
            focus_range: 100.0,
            max_blur_radius: 4.0,
            bokeh_threshold: 0.9,
            bokeh_intensity: 0.5,
            quality: DepthOfFieldQuality::Low,
            visualize_coc: false,
            tilt_shift_enabled: false,
            tilt_shift_angle: 0.0,
            tilt_shift_center: 0.0,
            tilt_shift_blur_amount: 1.0,
            visualize_tilt_shift: false,
        }
    }

    pub fn tilt_shift() -> Self {
        Self {
            enabled: true,
            focus_distance: 10.0,
            focus_range: 5.0,
            max_blur_radius: 12.0,
            bokeh_threshold: 0.8,
            bokeh_intensity: 0.8,
            quality: DepthOfFieldQuality::Medium,
            visualize_coc: false,
            tilt_shift_enabled: true,
            tilt_shift_angle: 0.0,
            tilt_shift_center: 0.0,
            tilt_shift_blur_amount: 1.0,
            visualize_tilt_shift: false,
        }
    }
}

/// HDR to LDR tonemapping algorithm.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
pub enum TonemapAlgorithm {
    /// Academy Color Encoding System (film-like).
    #[default]
    Aces,
    /// Simple Reinhard curve.
    Reinhard,
    /// Extended Reinhard with white point.
    ReinhardExtended,
    /// Filmic curve from Uncharted 2.
    Uncharted2,
    /// AgX display transform.
    AgX,
    /// Neutral (minimal color shift).
    Neutral,
    /// No tonemapping (clamp only).
    None,
}

impl TonemapAlgorithm {
    pub const ALL: &'static [TonemapAlgorithm] = &[
        TonemapAlgorithm::Aces,
        TonemapAlgorithm::Reinhard,
        TonemapAlgorithm::ReinhardExtended,
        TonemapAlgorithm::Uncharted2,
        TonemapAlgorithm::AgX,
        TonemapAlgorithm::Neutral,
        TonemapAlgorithm::None,
    ];

    pub fn as_u32(&self) -> u32 {
        match self {
            TonemapAlgorithm::Aces => 0,
            TonemapAlgorithm::Reinhard => 1,
            TonemapAlgorithm::ReinhardExtended => 2,
            TonemapAlgorithm::Uncharted2 => 3,
            TonemapAlgorithm::AgX => 4,
            TonemapAlgorithm::Neutral => 5,
            TonemapAlgorithm::None => 6,
        }
    }

    pub fn name(&self) -> &'static str {
        match self {
            TonemapAlgorithm::Aces => "ACES",
            TonemapAlgorithm::Reinhard => "Reinhard",
            TonemapAlgorithm::ReinhardExtended => "Reinhard Extended",
            TonemapAlgorithm::Uncharted2 => "Uncharted 2",
            TonemapAlgorithm::AgX => "AgX",
            TonemapAlgorithm::Neutral => "Neutral",
            TonemapAlgorithm::None => "None",
        }
    }
}

/// Pre-configured color grading style.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
pub enum ColorGradingPreset {
    /// Neutral default settings.
    #[default]
    Default,
    /// High saturation and brightness.
    Vibrant,
    /// Film-like with lifted blacks.
    Cinematic,
    /// Low saturation and contrast.
    Muted,
    /// Strong contrast with deep blacks.
    HighContrast,
    /// Orange-shifted warm tones.
    Warm,
    /// Blue-shifted cool tones.
    Cool,
    /// Faded vintage look.
    Retro,
    /// Nearly black and white.
    Desaturated,
    /// User-defined values.
    Custom,
}

impl ColorGradingPreset {
    pub const ALL: &'static [ColorGradingPreset] = &[
        ColorGradingPreset::Default,
        ColorGradingPreset::Vibrant,
        ColorGradingPreset::Cinematic,
        ColorGradingPreset::Muted,
        ColorGradingPreset::HighContrast,
        ColorGradingPreset::Warm,
        ColorGradingPreset::Cool,
        ColorGradingPreset::Retro,
        ColorGradingPreset::Desaturated,
        ColorGradingPreset::Custom,
    ];

    pub fn name(&self) -> &'static str {
        match self {
            ColorGradingPreset::Default => "Default",
            ColorGradingPreset::Vibrant => "Vibrant",
            ColorGradingPreset::Cinematic => "Cinematic",
            ColorGradingPreset::Muted => "Muted",
            ColorGradingPreset::HighContrast => "High Contrast",
            ColorGradingPreset::Warm => "Warm",
            ColorGradingPreset::Cool => "Cool",
            ColorGradingPreset::Retro => "Retro",
            ColorGradingPreset::Desaturated => "Desaturated",
            ColorGradingPreset::Custom => "Custom",
        }
    }

    pub fn to_color_grading(&self) -> ColorGrading {
        match self {
            ColorGradingPreset::Default => ColorGrading {
                gamma: 2.2,
                saturation: 1.0,
                brightness: 0.0,
                contrast: 1.0,
                tonemap_algorithm: TonemapAlgorithm::Aces,
                preset: *self,
            },
            ColorGradingPreset::Vibrant => ColorGrading {
                gamma: 2.2,
                saturation: 1.3,
                brightness: 0.02,
                contrast: 1.1,
                tonemap_algorithm: TonemapAlgorithm::Aces,
                preset: *self,
            },
            ColorGradingPreset::Cinematic => ColorGrading {
                gamma: 2.4,
                saturation: 0.9,
                brightness: -0.02,
                contrast: 1.15,
                tonemap_algorithm: TonemapAlgorithm::Aces,
                preset: *self,
            },
            ColorGradingPreset::Muted => ColorGrading {
                gamma: 2.2,
                saturation: 0.7,
                brightness: 0.0,
                contrast: 0.9,
                tonemap_algorithm: TonemapAlgorithm::Reinhard,
                preset: *self,
            },
            ColorGradingPreset::HighContrast => ColorGrading {
                gamma: 2.2,
                saturation: 1.1,
                brightness: 0.0,
                contrast: 1.4,
                tonemap_algorithm: TonemapAlgorithm::Aces,
                preset: *self,
            },
            ColorGradingPreset::Warm => ColorGrading {
                gamma: 2.1,
                saturation: 1.1,
                brightness: 0.03,
                contrast: 1.05,
                tonemap_algorithm: TonemapAlgorithm::Aces,
                preset: *self,
            },
            ColorGradingPreset::Cool => ColorGrading {
                gamma: 2.3,
                saturation: 0.95,
                brightness: -0.01,
                contrast: 1.05,
                tonemap_algorithm: TonemapAlgorithm::Neutral,
                preset: *self,
            },
            ColorGradingPreset::Retro => ColorGrading {
                gamma: 2.0,
                saturation: 0.8,
                brightness: 0.05,
                contrast: 1.2,
                tonemap_algorithm: TonemapAlgorithm::Reinhard,
                preset: *self,
            },
            ColorGradingPreset::Desaturated => ColorGrading {
                gamma: 2.2,
                saturation: 0.3,
                brightness: 0.0,
                contrast: 1.0,
                tonemap_algorithm: TonemapAlgorithm::Aces,
                preset: *self,
            },
            ColorGradingPreset::Custom => ColorGrading::default(),
        }
    }
}

/// Color grading and tonemapping settings.
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
pub struct ColorGrading {
    /// Gamma correction exponent (typically 2.2).
    pub gamma: f32,
    /// Color saturation multiplier (1.0 = neutral).
    pub saturation: f32,
    /// Brightness offset (-1 to 1).
    pub brightness: f32,
    /// Contrast multiplier (1.0 = neutral).
    pub contrast: f32,
    /// HDR tonemapping algorithm.
    pub tonemap_algorithm: TonemapAlgorithm,
    /// Active preset (Custom if manually adjusted).
    pub preset: ColorGradingPreset,
}

impl Default for ColorGrading {
    fn default() -> Self {
        Self {
            gamma: 2.2,
            saturation: 1.0,
            brightness: 0.0,
            contrast: 1.0,
            tonemap_algorithm: TonemapAlgorithm::Aces,
            preset: ColorGradingPreset::Default,
        }
    }
}

/// PS1-style vertex snapping for retro rendering.
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
pub struct VertexSnap {
    /// Grid resolution to snap vertices to (lower = more pixelated).
    pub resolution: [f32; 2],
}

impl Default for VertexSnap {
    fn default() -> Self {
        Self {
            resolution: [160.0, 120.0],
        }
    }
}

/// Distance-based fog settings.
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
pub struct Fog {
    /// Fog color (linear RGB).
    pub color: [f32; 3],
    /// Distance where fog begins.
    pub start: f32,
    /// Distance where fog is fully opaque.
    pub end: f32,
}

impl Default for Fog {
    fn default() -> Self {
        Self {
            color: [0.5, 0.5, 0.55],
            start: 2.0,
            end: 15.0,
        }
    }
}

/// Skybox and environment map selection.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
pub enum Atmosphere {
    /// Solid background color (no skybox).
    #[default]
    None,
    /// Procedural clear sky gradient.
    Sky,
    /// Procedural sky with volumetric clouds.
    CloudySky,
    /// Procedural starfield.
    Space,
    /// Procedural nebula with stars.
    Nebula,
    /// Procedural sunset gradient.
    Sunset,
    /// HDR environment cubemap.
    Hdr,
    /// Debug: HDR mip level 0.
    HdrMip0,
    /// Debug: HDR mip level 1.
    HdrMip1,
    /// Debug: HDR mip level 2.
    HdrMip2,
    /// Debug: HDR mip level 3.
    HdrMip3,
    /// Debug: HDR mip level 4.
    HdrMip4,
    /// Debug: Diffuse irradiance map.
    Irradiance,
    /// Debug: Prefiltered specular mip 0.
    PrefilterMip0,
    /// Debug: Prefiltered specular mip 1.
    PrefilterMip1,
    /// Debug: Prefiltered specular mip 2.
    PrefilterMip2,
    /// Debug: Prefiltered specular mip 3.
    PrefilterMip3,
    /// Debug: Prefiltered specular mip 4.
    PrefilterMip4,
}

impl Atmosphere {
    pub const ALL: &'static [Atmosphere] = &[
        Atmosphere::None,
        Atmosphere::Sky,
        Atmosphere::CloudySky,
        Atmosphere::Space,
        Atmosphere::Nebula,
        Atmosphere::Sunset,
        Atmosphere::Hdr,
        Atmosphere::HdrMip0,
        Atmosphere::HdrMip1,
        Atmosphere::HdrMip2,
        Atmosphere::HdrMip3,
        Atmosphere::HdrMip4,
        Atmosphere::Irradiance,
        Atmosphere::PrefilterMip0,
        Atmosphere::PrefilterMip1,
        Atmosphere::PrefilterMip2,
        Atmosphere::PrefilterMip3,
        Atmosphere::PrefilterMip4,
    ];

    pub fn mip_level(&self) -> f32 {
        match self {
            Atmosphere::HdrMip0 | Atmosphere::PrefilterMip0 => 0.0,
            Atmosphere::HdrMip1 | Atmosphere::PrefilterMip1 => 1.0,
            Atmosphere::HdrMip2 | Atmosphere::PrefilterMip2 => 2.0,
            Atmosphere::HdrMip3 | Atmosphere::PrefilterMip3 => 3.0,
            Atmosphere::HdrMip4 | Atmosphere::PrefilterMip4 => 4.0,
            _ => 0.0,
        }
    }

    pub fn next(self) -> Self {
        let all = Self::ALL;
        let current_index = all.iter().position(|&a| a == self).unwrap_or(0);
        let next_index = (current_index + 1) % all.len();
        all[next_index]
    }

    pub fn previous(self) -> Self {
        let all = Self::ALL;
        let current_index = all.iter().position(|&a| a == self).unwrap_or(0);
        let prev_index = if current_index == 0 {
            all.len() - 1
        } else {
            current_index - 1
        };
        all[prev_index]
    }

    pub fn is_procedural(&self) -> bool {
        matches!(
            self,
            Atmosphere::Sky
                | Atmosphere::CloudySky
                | Atmosphere::Space
                | Atmosphere::Nebula
                | Atmosphere::Sunset
        )
    }

    pub fn as_procedural_cubemap_type(&self) -> Option<u32> {
        match self {
            Atmosphere::Sky => Some(0),
            Atmosphere::CloudySky => Some(1),
            Atmosphere::Space => Some(2),
            Atmosphere::Nebula => Some(3),
            Atmosphere::Sunset => Some(4),
            _ => None,
        }
    }
}

/// Global graphics and rendering settings.
pub struct Graphics {
    /// Enable compute shader grayscale post-processing.
    pub compute_grayscale_enabled: bool,
    /// Enable GPU frustum culling.
    pub gpu_culling_enabled: bool,
    /// Enable Hi-Z occlusion culling.
    pub occlusion_culling_enabled: bool,
    /// Show debug grid overlay.
    pub show_grid: bool,
    /// Show bounding volumes for all entities.
    pub show_bounding_volumes: bool,
    /// Show bounding volume for selected entity only.
    pub show_selected_bounding_volume: bool,
    /// Entity to highlight with bounding volume.
    pub bounding_volume_selected_entity: Option<freecs::Entity>,
    /// Show vertex normal debug lines.
    pub show_normals: bool,
    /// Length of normal debug lines.
    pub normal_line_length: f32,
    /// Color for normal debug lines.
    pub normal_line_color: [f32; 4],
    /// Active skybox/environment map.
    pub atmosphere: Atmosphere,
    /// Enable world render layer.
    pub render_layer_world_enabled: bool,
    /// Enable overlay render layer.
    pub render_layer_overlay_enabled: bool,
    /// Use fullscreen mode.
    pub use_fullscreen: bool,
    /// Show the mouse cursor.
    pub show_cursor: bool,
    /// Background clear color.
    pub clear_color: [f32; 4],
    /// Override UI scale factor (None = automatic).
    pub ui_scale: Option<f32>,
    /// Current letterbox amount (0-1).
    pub letterbox_amount: f32,
    /// Target letterbox amount for animation.
    pub letterbox_target: f32,
    /// Disable all lighting calculations.
    pub unlit_mode: bool,
    /// Enable selection outline effect.
    pub selection_outline_enabled: bool,
    /// Selection outline color.
    pub selection_outline_color: [f32; 4],
    /// PS1-style vertex snapping settings.
    pub vertex_snap: Option<VertexSnap>,
    /// PS1-style affine texture mapping.
    pub affine_texture_mapping: bool,
    /// Distance fog settings.
    pub fog: Option<Fog>,
    /// Color grading and tonemapping.
    pub color_grading: ColorGrading,
    /// Enable bloom post-processing.
    pub bloom_enabled: bool,
    /// Bloom intensity multiplier.
    pub bloom_intensity: f32,
    /// Depth of field settings.
    pub depth_of_field: DepthOfField,
    /// Enable screen-space ambient occlusion.
    pub ssao_enabled: bool,
    /// SSAO sample radius in world units.
    pub ssao_radius: f32,
    /// SSAO depth bias to reduce self-occlusion.
    pub ssao_bias: f32,
    /// SSAO darkening intensity.
    pub ssao_intensity: f32,
    /// PBR debug visualization mode.
    pub pbr_debug_mode: PbrDebugMode,
    /// Show animated debug stripes on textures.
    pub texture_debug_stripes: bool,
    /// Animation speed for debug stripes.
    pub texture_debug_stripes_speed: f32,
}

impl Default for Graphics {
    fn default() -> Self {
        Self {
            compute_grayscale_enabled: false,
            gpu_culling_enabled: true,
            occlusion_culling_enabled: true,
            show_grid: false,
            show_bounding_volumes: false,
            show_selected_bounding_volume: false,
            bounding_volume_selected_entity: None,
            show_normals: false,
            normal_line_length: 0.1,
            normal_line_color: [0.0, 1.0, 0.0, 1.0],
            atmosphere: Atmosphere::None,
            render_layer_world_enabled: true,
            render_layer_overlay_enabled: true,
            use_fullscreen: false,
            show_cursor: true,
            clear_color: [0.0, 0.0, 0.0, 1.0],
            ui_scale: None,
            letterbox_amount: 0.0,
            letterbox_target: 0.0,
            unlit_mode: false,
            selection_outline_enabled: false,
            selection_outline_color: [1.0, 0.45, 0.0, 1.0],
            vertex_snap: None,
            affine_texture_mapping: false,
            fog: None,
            color_grading: ColorGrading::default(),
            bloom_enabled: false,
            bloom_intensity: 0.3,
            depth_of_field: DepthOfField::default(),
            ssao_enabled: false,
            ssao_radius: 0.5,
            ssao_bias: 0.025,
            ssao_intensity: 1.0,
            pbr_debug_mode: PbrDebugMode::None,
            texture_debug_stripes: false,
            texture_debug_stripes_speed: 100.0,
        }
    }
}
