//! Material-slot and schema-driven parameter widgets shared by production and the gallery.

use bevy_math::{Vec2, Vec3};
use egui;
use egui_phosphor_icons::Icon;
use material_schema::{
    ColorDesc, EditorAssetRef, MaterialInputDesc, MaterialInputSchema, MaterialInputSet,
    MaterialParameter, MaterialParameterValue, MaterialTextureBinding, ShaderPropertyType,
    TextureChannel,
};

use crate::theme::TEXT_DIM;

mod advanced_preview;
mod inputs;
mod layout;
mod panel;
mod pickers;
mod surface;
mod texture_inputs;
mod uv_transform;

pub use inputs::{
    apply_arm_texture_preset, apply_separate_texture_preset, compact_text_edit,
    default_value_for_shader_property, material_input_schema_editor,
    material_input_schema_editor_with_inheritance, optional_path_edit, packed_map_mode,
    parameter_value_matches_property, shader_kind_combo, shader_kind_picker, PackedMapMode,
};
pub use panel::{
    material_slot_panel, materials_section, MaterialHealth, MaterialLayerBadge,
    MaterialPickerCandidate, MaterialSlotAction, MaterialSlotPanelAction,
    MaterialSlotPanelResponse, MaterialSlotPanelViewModel, MaterialsSectionViewModel,
};
pub use surface::material_surface_options_ui;
pub use texture_inputs::ensure_material_texture_binding;

#[derive(Clone, Debug, PartialEq, Eq)]
pub enum MaterialLocateTarget {
    File(String),
    SubAsset {
        parent_path: String,
        sub_asset_id: String,
        label: String,
        source_path: Option<String>,
    },
}

#[derive(Clone, Debug)]
pub struct MaterialTextureCandidate {
    pub label: String,
    pub detail: String,
    pub reference: EditorAssetRef,
    pub locate: MaterialLocateTarget,
    pub thumbnail: MaterialThumbnailPresentation,
}

#[derive(Default)]
pub struct MaterialInputEditorResponse {
    pub accepted_drop: bool,
    pub locate: Option<MaterialLocateTarget>,
    pub browse_library: bool,
}

#[derive(Clone, Copy, Debug, PartialEq)]
pub enum MaterialThumbnailPresentation {
    Ready(egui::TextureId),
    Pending,
    Failed,
    Empty,
}

#[derive(Clone, Copy)]
enum TextureSlotSelection<'a> {
    Reference(Option<&'a EditorAssetRef>),
}

#[derive(Default)]
struct TextureSlotResponse {
    selected: Option<MaterialTextureCandidate>,
    locate: Option<MaterialLocateTarget>,
    clear: bool,
    accepted_drop: bool,
    browse_library: bool,
}

fn fit_width(ui: &egui::Ui, min: f32, max: f32) -> f32 {
    let available = ui.available_width().max(1.0);
    available.min(max).max(min.min(available))
}

fn icon_text(icon: Icon, size: f32) -> egui::RichText {
    egui::RichText::new(icon.as_str()).font(egui::FontId::new(
        size,
        egui::FontFamily::Name("phosphor-bold".into()),
    ))
}
