#include "Inspector.h"

#include "../../Entitys/Object.h"
#include "../../components/SpriteComponent.h"
#include "../../components/CameraComponent.h"
#include "../../components/LightComponent.h"
#include "../../components/TilemapComponent.h"
#include "../../components/ScriptComponent.h"
#include "../../components/PhysicsComponent.h"
#include "../../components/ParticleComponent.h"
#include "../../components/AnimationComponent.h"
#include "../../components/AudioPlayerComponent.h"

#include "imgui.h"
#include "imgui_internal.h"

#include <iostream>



void DrawInspectorUI(std::shared_ptr<Object> selected)
{

    PROFILE_ENGINE_SCOPE("Engine::DrawInspectorUI");
    ImGui::Begin("Inspector", nullptr, ImGuiWindowFlags_NoScrollbar);

    if (!selected)
    {
        ImGui::TextDisabled("No object selected.");
        ImGui::End();
        return;
    }

    // --- keep track of the name buffer ---
    static char nameBuffer[128] = "";
    static std::shared_ptr<Object> lastSelected = nullptr;
    if (selected != lastSelected)
    {
        strncpy(nameBuffer, selected->GetName().c_str(), sizeof(nameBuffer));
        nameBuffer[sizeof(nameBuffer) - 1] = '\0';
        lastSelected = selected;
    }

    // --- General ---
    ImGui::TextUnformatted("General");
    ImGui::Separator();

    // Name edit
    if (ImGui::InputText("Name", nameBuffer, sizeof(nameBuffer)))
        selected->SetName(nameBuffer);

    // Visibility toggle
    bool visible = selected->GetVisable();
    if (ImGui::Checkbox("Visible", &visible))
        selected->SetVisable(visible);

    // --- Transform ---
    ImGui::TextUnformatted("Transform");
    ImGui::Separator();

    glm::vec2 pos = selected->GetLocalPosition();
    if (ImGui::DragFloat2("Position", &pos.x, 0.1f))
        selected->SetLocalPosition(pos);

    float rotation = selected->GetLocalRotation();
    if (ImGui::DragFloat("Rotation", &rotation, 1.0f))
        selected->SetLocalRotation(rotation);

    int layer = selected->layer;
    if (ImGui::InputInt("Layer", &layer))
        selected->layer = layer;

    ImGui::Text("ID: %d", selected->uid.id);
    ImGui::Text("UID: %s", selected->uid.uuid.c_str());

    ImGui::Spacing();
    ImGui::SeparatorText("Add Component");

    static const char *componentTypes[] = {
        "Sprite",
        "Camera",
        "Light",
        "Script",
        "Tilemap",
        "Particle",
        "Animation",
        "Audio Player"};

    static int selectedIndex = -1;

    if (ImGui::BeginCombo("##ComponentCombo", selectedIndex >= 0 ? componentTypes[selectedIndex] : "Select Component"))
    {
        for (int i = 0; i < IM_ARRAYSIZE(componentTypes); ++i)
        {
            bool isSelected = (selectedIndex == i);
            if (ImGui::Selectable(componentTypes[i], isSelected))
                selectedIndex = i;
            if (isSelected)
                ImGui::SetItemDefaultFocus();
        }
        ImGui::EndCombo();
    }

    ImGui::SameLine();
    if (ImGui::Button("Add") && selectedIndex != -1 && selected)
    {
        const std::string type = componentTypes[selectedIndex];

        if (type == "Sprite" && !selected->GetComponent<SpriteComponent>())
            selected->AddComponent<SpriteComponent>();
        else if (type == "Camera" && !selected->GetComponent<CameraComponent>())
            selected->AddComponent<CameraComponent>();
        else if (type == "Light" && !selected->GetComponent<LightComponent>())
            selected->AddComponent<LightComponent>();
        else if (type == "Script" && !selected->GetComponent<ScriptComponent>())
            selected->AddComponent<ScriptComponent>();
        else if (type == "Tilemap" && !selected->GetComponent<TilemapComponent>())
            selected->AddComponent<TilemapComponent>();
        else if (type == "Particle" && !selected->GetComponent<ParticleComponent>())
            selected->AddComponent<ParticleComponent>();
        else if (type == "Animation" && !selected->GetComponent<AnimationComponent>())
            selected->AddComponent<AnimationComponent>();
        else if (type == "Audio Player" && !selected->GetComponent<AudioPlayerComponent>())
            selected->AddComponent<AudioPlayerComponent>();
            
    }

    if (auto sprite = selected->GetComponent<SpriteComponent>())
    {
        ImGui::SeparatorText("Sprite Component");

        const char *renderTypes[] = {"Unlit", "Lit"};
        int currentTypeIndex = static_cast<int>(sprite->GetRenderType());
        if (ImGui::Combo("Render Type", &currentTypeIndex, renderTypes, IM_ARRAYSIZE(renderTypes)))
            sprite->SetRenderType(static_cast<RenderType>(currentTypeIndex));

        ImGui::SeparatorText("Texture");
        {
            const AssetInfo *asset = AssetManager::GetAssetByID(sprite->GetTextureUAID());
            std::string texFile = asset ? GetFilenameFromPath(asset->path) : "(None)";
            ImGui::Text("%s", texFile.c_str());

            if (ImGui::BeginDragDropTarget())
            {
                if (const ImGuiPayload *payload = ImGui::AcceptDragDropPayload("ASSET_TEXTURE"))
                {
                    if (payload->DataSize == sizeof(uint64_t))
                    {
                        uint64_t uaid = *reinterpret_cast<const uint64_t *>(payload->Data);
                        sprite->SetTexture(uaid);
                    }
                }
                ImGui::EndDragDropTarget();
            }

            if (ImGui::SmallButton("Load##SpriteTex"))
            {
                auto path = OpenFileDialog(FileDialogType::Images);
                if (!path.empty())
                    sprite->SetTexture(path);
            }
        }

        ImGui::SeparatorText("Normal Map");
        {
            const AssetInfo *asset = AssetManager::GetAssetByID(sprite->GetNormalMapUAID());
            std::string normFile = asset ? GetFilenameFromPath(asset->path) : "(None)";
            ImGui::Text("%s", normFile.c_str());

            if (ImGui::BeginDragDropTarget())
            {
                if (const ImGuiPayload *payload = ImGui::AcceptDragDropPayload("ASSET_TEXTURE"))
                {
                    if (payload->DataSize == sizeof(uint64_t))
                    {
                        uint64_t uaid = *reinterpret_cast<const uint64_t *>(payload->Data);
                        sprite->SetNormalMap(uaid);
                    }
                }
                ImGui::EndDragDropTarget();
            }

            if (ImGui::SmallButton("Load##SpriteNorm"))
            {
                auto path = OpenFileDialog(FileDialogType::Images);
                if (!path.empty())
                    sprite->SetNormalMap(path); // Auto-registers and sets UAID
            }
        }

        ImGui::SeparatorText("Info");

        glm::vec2 size = sprite->GetSize();
        ImGui::Text("Size: %.0f × %.0f", size.x, size.y);

        ImGui::Separator();

        if (ImGui::Button("Remove SpriteComponent"))
            selected->RemoveComponent<SpriteComponent>();
    }

    if (auto cam = selected->GetComponent<CameraComponent>())
    {
        ImGui::SeparatorText("Camera Component");

        float fov = cam->GetFOV();
        float aspect = cam->GetAspect();
        float zoom = cam->GetZoom();

        if (ImGui::DragFloat("FOV", &fov, 0.1f, 1.0f, 179.0f))
            cam->SetFOV(fov);
        if (ImGui::DragFloat("Aspect", &aspect, 0.01f, 0.1f, 5.0f))
            cam->SetAspect(aspect);
        if (ImGui::DragFloat("Zoom", &zoom, 0.1f, 0.1f, 10.0f))
            cam->SetZoom(zoom);

        bool isPrimary = cam->IsPrimary();
        if (ImGui::Checkbox("Primary", &isPrimary))
            cam->SetPrimary(isPrimary);

        if (ImGui::Button("Remove CameraComponent"))
            selected->RemoveComponent<CameraComponent>();
    }

    if (auto light = selected->GetComponent<LightComponent>())
    {
        ImGui::SeparatorText("Light Component");

        glm::vec3 color = light->GetColor();
        float intensity = light->GetIntensity();
        float radius = light->GetRadius();
        float falloff = light->GetFalloff();
        int type = light->GetType();

        if (ImGui::ColorEdit3("Color", &color.x))
            light->SetColor(color);
        if (ImGui::DragFloat("Intensity", &intensity, 0.05f, 0.0f, 10.0f))
            light->SetIntensity(intensity);
        if (ImGui::DragFloat("Radius", &radius, 1.0f, 10.0f, 1000.0f))
            light->SetRadius(radius);
        if (ImGui::DragFloat("Falloff", &falloff, 0.05f, 0.1f, 5.0f))
            light->SetFalloff(falloff);

        // const char* types[] = { "Point", "Directional" };
        // if (ImGui::Combo("Type", &type, types, IM_ARRAYSIZE(types)))
        //     light->SetType(type);

        if (ImGui::Button("Remove LightComponent"))
            selected->RemoveComponent<LightComponent>();
    }

    if (auto script = selected->GetComponent<ScriptComponent>())
    {
        ImGui::SeparatorText("Script Component");

        std::string path = script->GetScriptPath();
        ImGui::Text("Script Path:");
        ImGui::TextWrapped("%s", path.c_str());

        if (ImGui::Button("Load Script"))
        {
            std::string chosen = OpenFileDialog(FileDialogType::Scripts); // Add 'Scripts' filter if needed
            if (!chosen.empty())
                script->SetScriptPath(chosen);
        }

        ImGui::SameLine();
        if (ImGui::Button("Reload"))
        {
            script->ReloadScript();
        }

        if (ImGui::Button("Remove ScriptComponent"))
            selected->RemoveComponent<ScriptComponent>();
    }

    if (auto anim = selected->GetComponent<AnimationComponent>())
    {
        ImGui::SeparatorText("Animation Component");

        static int frameWidth = anim->GetAtlas()->frameWidth;
        static int frameHeight = anim->GetAtlas()->frameHeight;
        static float frameDuration = anim->GetFrameDuration();
        static int frameIndex = anim->GetCurrentFrame();
        static int startFrame = 0;
        static int endFrame = 0;

        ImGui::SeparatorText("Texture Atlas");

        {
            std::string texFile = "(None)";
            if (const auto *asset = AssetManager::GetAssetByID(anim->GetTextureUAID()))
                texFile = GetFilenameFromPath(asset->path);

            ImGui::Text("%s", texFile.c_str());

            if (ImGui::BeginDragDropTarget())
            {
                if (const ImGuiPayload *payload = ImGui::AcceptDragDropPayload("ASSET_TEXTURE"))
                {
                    uint64_t droppedUAID = *(const uint64_t *)payload->Data;
                    anim->SetTextureAtlas(droppedUAID, frameWidth, frameHeight, frameDuration, startFrame, endFrame);
                }
                ImGui::EndDragDropTarget();
            }

            if (ImGui::SmallButton("Load##AnimTex"))
            {
                std::string path = OpenFileDialog(FileDialogType::Images);
                if (const auto *asset = AssetManager::GetAssetByPath(path))
                    anim->SetTextureAtlas(asset->uaid, frameWidth, frameHeight, frameDuration, startFrame, endFrame);
            }
        }

        ImGui::InputInt("Texel Width", &frameWidth);
        ImGui::InputInt("Texel Height", &frameHeight);
        ImGui::InputFloat("Frame Duration", &frameDuration, 0.01f, 0.1f, "%.3f");

        ImGui::InputInt("Start Frame", &startFrame);
        ImGui::InputInt("End Frame", &endFrame);

        if (ImGui::Button("Apply"))
        {
            if (const auto *asset = AssetManager::GetAssetByID(anim->GetTextureUAID()))
                anim->SetTextureAtlas(asset->uaid, frameWidth, frameHeight, frameDuration, startFrame, endFrame);
        }

        ImGui::SeparatorText("Playback");

        bool isPlaying = anim->IsPlaying();
        if (ImGui::Checkbox("Playing", &isPlaying))
        {
            isPlaying ? anim->Play() : anim->Stop();
        }

        bool loop = anim->IsLooping();
        if (ImGui::Checkbox("Loop", &loop))
        {
            anim->SetLooping(loop);
        }

        float speed = anim->GetSpeed();
        if (ImGui::SliderFloat("Speed", &speed, 0.1f, 5.0f))
        {
            anim->SetSpeed(speed);
        }

        // Frame scrubber
        int maxFrame = anim->GetAtlas()->GetTotalFrames() - 1;
        frameIndex = anim->GetCurrentFrame();
        if (ImGui::SliderInt("Current Frame", &frameIndex, 0, maxFrame))
        {
            anim->SetFrame(frameIndex);
        }

        // — Atlas Viewer —
        if (anim->GetAtlas()->texture)
        {
            ImGui::SeparatorText("Atlas Viewer");

            const float previewSize = 128.0f;
            core::types::Vec2 uvMin = anim->GetAtlas()->GetFrameUV(frameIndex);
            core::types::Vec2 uvSize = anim->GetAtlas()->GetFrameSizeUV();

            ImVec2 uv0 = ImVec2(uvMin.x, uvMin.y + uvSize.y);
            ImVec2 uv1 = ImVec2(uvMin.x + uvSize.x, uvMin.y);

            ImGui::Image((ImTextureID)(intptr_t)anim->GetAtlas()->texture->GetID(), ImVec2(previewSize, previewSize), uv1, uv0);
        }

        ImGui::Separator();

        if (ImGui::Button("Remove AnimationComponent"))
            selected->RemoveComponent<AnimationComponent>();
    }

    if (auto part = selected->GetComponent<ParticleComponent>())
    {
        ImGui::SeparatorText("Particle Component");

        auto settings = part->GetEmitterSettings();

        ImGui::DragInt("Max Particles", &settings.maxParticles, 10, 10, 10000);
        ImGui::DragFloat("Emission Rate", &settings.emissionRate, 1.0f, 0.0f, 1000.0f);
        ImGui::DragFloat("Life Min", &settings.lifeMin, 0.01f, 0.01f, 10.0f);
        ImGui::DragFloat("Life Max", &settings.lifeMax, 0.01f, 0.01f, 10.0f);
        ImGui::DragFloat("Size Min", &settings.sizeMin, 0.1f, 0.1f, 100.0f);
        ImGui::DragFloat("Size Max", &settings.sizeMax, 0.1f, 0.1f, 100.0f);
        ImGui::DragFloat("Speed Min", &settings.speedMin, 1.0f, 0.0f, 1000.0f);
        ImGui::DragFloat("Speed Max", &settings.speedMax, 1.0f, 0.0f, 1000.0f);

        {
            float directionAngleDeg = glm::degrees(std::atan2(settings.direction.y, settings.direction.x));

            if (directionAngleDeg < 0.0f)
                directionAngleDeg += 360.0f;

            if (ImGui::DragFloat("Direction", &directionAngleDeg, 0.5f, 0.0f, 360.0f))
            {
                float rad = glm::radians(directionAngleDeg);
                settings.direction.x = std::cos(rad);
                settings.direction.y = std::sin(rad);
            }
        }

        {
            float spreadDeg = glm::degrees(settings.spread);
            if (ImGui::DragFloat("Spread", &spreadDeg, 0.5f, 0.0f, 360.0f))
            {
                settings.spread = glm::radians(spreadDeg);
            }
        }

        ImGui::ColorEdit4("Start Color", &settings.startColor.r);
        ImGui::ColorEdit4("End Color", &settings.endColor.r);

        bool isRound = settings.roundness > 0.5f;
        if (ImGui::Checkbox("Circle", &isRound))
            settings.roundness = isRound ? 1.0f : 0.0f;

        ImGui::Checkbox("Loop", &settings.loop);
        ImGui::Checkbox("Burst", &settings.burst);

        part->SetEmitterSettings(settings);

        if (ImGui::Button("Emit Once"))
            part->Emit();

        if (ImGui::Button("Remove ParticleComponent"))
            selected->RemoveComponent<ParticleComponent>();
    }

    if (auto phys = selected->GetComponent<PhysicsComponent>())
    {
        ImGui::SeparatorText("Physics Component");

        glm::vec2 vel = phys->GetVelocity();
        if (ImGui::DragFloat2("Velocity", &vel.x))
            phys->SetVelocity(vel);

        float friction = phys->GetFriction();
        if (ImGui::DragFloat("Friction", &friction, 0.01f, 0.0f, 1.0f))
            phys->SetFriction(friction);

        bool fixed = phys->IsFixedRotation();
        if (ImGui::Checkbox("Fixed Rotation", &fixed))
            phys->SetFixedRotation(fixed);

        if (ImGui::Button("Remove PhysicsComponent"))
            selected->RemoveComponent<PhysicsComponent>();
    }

    if (auto tilemap = selected->GetComponent<TilemapComponent>())
    {
        ImGui::SeparatorText("Tilemap Component");

        int texelWidth = (int)tilemap->GetTileSize().x;
        int texelHeight = (int)tilemap->GetTileSize().y;
        core::types::Vec2 tileSize = tilemap->GetTileSize();

        uint64_t uaid = tilemap->GetTextureUAID();
        const auto *asset = AssetManager::GetAssetByID(uaid);

        ImGui::SeparatorText("Texture Atlas");

        std::string texFile = asset ? GetFilenameFromPath(asset->path) : "(None)";
        ImGui::Text("%s", texFile.c_str());

        // Drag and drop texture
        if (ImGui::BeginDragDropTarget())
        {
            if (const ImGuiPayload *payload = ImGui::AcceptDragDropPayload("ASSET_TEXTURE"))
            {
                if (payload->DataSize == sizeof(uint64_t))
                {
                    uint64_t newUaid = *(const uint64_t *)payload->Data;
                    tilemap->SetTextureAtlas(newUaid, texelWidth, texelHeight);
                }
            }
            ImGui::EndDragDropTarget();
        }

        // Load from dialog
        if (ImGui::SmallButton("Load##TilemapTex"))
        {
            std::string path = OpenFileDialog(FileDialogType::Images);
            if (const auto *loaded = AssetManager::GetAssetByPath(path))
                tilemap->SetTextureAtlas(loaded->uaid, texelWidth, texelHeight);
        }

        if (ImGui::DragFloat2("Tile Size", &tileSize.x, 1.0f, 1.0f, 512.0f))
            tilemap->SetTileSize(tileSize);

        // Re-apply
        if (ImGui::Button("Apply"))
        {
            if (const auto *texAsset = AssetManager::GetAssetByID(tilemap->GetTextureUAID()))
                tilemap->SetTextureAtlas(texAsset->uaid, texelWidth, texelHeight);
        }

        if (auto texture = tilemap->GetTexture(); texture && texture.use_count() > 0 && texture->GetID() != 0)
        {
            ImGui::SeparatorText("Atlas Preview");

            ImTextureID texID = (ImTextureID)(uintptr_t)texture->GetID();
            core::types::Vec2 texSize = texture->GetSize();

            int texWidth = (int)texSize.x;
            int texHeight = (int)texSize.y;

            // Validate texel size
            if (texelWidth <= 0 || texelHeight <= 0)
            {
                ImGui::TextColored(ImVec4(1, 0.4f, 0.4f, 1), "Invalid texel size (must be >= 1)");
                ImGui::Separator();
                return;
            }

            int numCols = texWidth / texelWidth;
            int numRows = texHeight / texelHeight;
            if (numCols == 0 || numRows == 0)
            {
                ImGui::TextColored(ImVec4(1, 0.4f, 0.4f, 1), "Texel size too large for atlas resolution.");
                ImGui::Separator();
                return;
            }

            // Maintain aspect ratio
            float previewSize = ImGui::GetContentRegionAvail().x * 0.98;
            float aspect = texHeight / (float)texWidth;
            ImVec2 imageSize(previewSize, previewSize * aspect);
            ImVec2 imagePos = ImGui::GetCursorScreenPos();

            // Draw the atlas
            ImGui::Image(texID, imageSize);

            // Grid cell size in pixels
            float scaleX = imageSize.x / (float)texWidth;
            float scaleY = imageSize.y / (float)texHeight;
            float cellW = texelWidth * scaleX;
            float cellH = texelHeight * scaleY;

            ImDrawList *drawList = ImGui::GetWindowDrawList();
            const ImU32 gridColor = IM_COL32(255, 255, 255, 48);
            int linesDrawn = 0;

            // Vertical grid lines
            for (int col = 0; col <= numCols; ++col)
            {
                float x = imagePos.x + col * cellW;
                if (x > imagePos.x + imageSize.x)
                    break;
                drawList->AddLine(
                    ImVec2(x, imagePos.y),
                    ImVec2(x, imagePos.y + imageSize.y),
                    gridColor);
                linesDrawn++;
            }

            // Horizontal grid lines
            for (int row = 0; row <= numRows; ++row)
            {
                float y = imagePos.y + row * cellH;
                if (y > imagePos.y + imageSize.y)
                    break;
                drawList->AddLine(
                    ImVec2(imagePos.x, y),
                    ImVec2(imagePos.x + imageSize.x, y),
                    gridColor);
                linesDrawn++;
            }

            // ─────── Hover & Selection State ───────
            static bool selecting = false;
            static bool hasSelection = false;
            static int selStartX = 0, selStartY = 0, selEndX = 0, selEndY = 0;

            ImVec2 mousePos = ImGui::GetMousePos();
            bool mouseOver = ImGui::IsItemHovered();

            // Convert mouse → tile coords
            int tileX = (int)((mousePos.x - imagePos.x) / cellW);
            int tileY = (int)((mousePos.y - imagePos.y) / cellH);

            // ─ Hover highlight (yellow glow) ─
            if (mouseOver && tileX >= 0 && tileX < numCols && tileY >= 0 && tileY < numRows)
            {
                ImVec2 min(
                    imagePos.x + tileX * cellW,
                    imagePos.y + tileY * cellH);
                ImVec2 max(
                    min.x + cellW,
                    min.y + cellH);
                drawList->AddRectFilled(min, max, IM_COL32(255, 255, 0, 64), 2.0f);
                drawList->AddRect(min, max, IM_COL32(255, 255, 0, 128), 2.0f);
            }

            // ─ Drag‐to‐select & single‐click selection ─
            if (mouseOver)
            {
                if (ImGui::IsMouseClicked(ImGuiMouseButton_Left))
                {
                    selecting = true;
                    hasSelection = true;
                    selStartX = selEndX = tileX;
                    selStartY = selEndY = tileY;
                }
                if (selecting && ImGui::IsMouseDragging(ImGuiMouseButton_Left))
                {
                    selEndX = tileX;
                    selEndY = tileY;
                }
                if (selecting && ImGui::IsMouseReleased(ImGuiMouseButton_Left))
                {
                    selecting = false;
                }
            }

            // ─ Draw selection rectangle ─
            if (hasSelection)
            {
                int x0 = std::min(selStartX, selEndX);
                int y0 = std::min(selStartY, selEndY);
                int x1 = std::max(selStartX, selEndX);
                int y1 = std::max(selStartY, selEndY);

                ImVec2 selMin(
                    imagePos.x + x0 * cellW,
                    imagePos.y + y0 * cellH);
                ImVec2 selMax(
                    imagePos.x + (x1 + 1) * cellW,
                    imagePos.y + (y1 + 1) * cellH);

                drawList->AddRectFilled(selMin, selMax, IM_COL32(0, 255, 255, 32));
                drawList->AddRect(selMin, selMax, IM_COL32(0, 255, 255, 128), 2.0f);
            }

            // ─ Hover‐tile preview ─
            if (mouseOver && tileX >= 0 && tileX < numCols && tileY >= 0 && tileY < numRows)
            {
                ImGui::SeparatorText("Hovered Tile");
                ImVec2 uv0(
                    tileX * (float)texelWidth / texWidth,
                    tileY * (float)texelHeight / texHeight);
                ImVec2 uv1(
                    (tileX + 1) * (float)texelWidth / texWidth,
                    (tileY + 1) * (float)texelHeight / texHeight);
                ImGui::Image(texID, ImVec2(64, 64), uv0, uv1);
            }
            else
            {
                ImGui::SeparatorText("Hovered Tile");

                ImGui::Dummy(ImVec2(64, 64));
            }

            tilemap->hasSelection = hasSelection;
            if (hasSelection)
            {
                int x0 = std::min(selStartX, selEndX);
                int y0 = std::min(selStartY, selEndY);
                int x1 = std::max(selStartX, selEndX);
                int y1 = std::max(selStartY, selEndY);

                tilemap->SetSelection(x0, y0, x1, y1);

                ImGui::SeparatorText("Selection Preview");
                ImVec2 uv0(
                    x0 * (float)texelWidth / texWidth,
                    y0 * (float)texelHeight / texHeight);
                ImVec2 uv1(
                    (x1 + 1) * (float)texelWidth / texWidth,
                    (y1 + 1) * (float)texelHeight / texHeight);
                ImVec2 imgSz(
                    (x1 - x0 + 1) * (float)texelWidth * scaleX,
                    (y1 - y0 + 1) * (float)texelHeight * scaleY);
                ImGui::Image(texID, imgSz, uv0, uv1);
            }
            else
            {
                tilemap->ClearSelection();
            }

            ImGui::Text("Atlas Resolution: %d x %d", texWidth, texHeight);
            if (mouseOver && tileX >= 0 && tileX < numCols && tileY >= 0 && tileY < numRows)
            {
                ImGui::Text("Selected Tile: %d x %d (%d)", tileX, tileY, (tileX * tileY));
            }
            ImGui::Text("Tile Grid:        %d x %d", numCols, numRows);
            ImGui::Text("Grid Lines:       %d", linesDrawn);

            ImGui::Separator();
        }
        else
        {
            ImGui::TextColored(ImVec4(1, 0.4f, 0.4f, 1), "Texture is missing or not loaded properly.");
            ImGui::Separator();
        }

        ImGui::Separator();
        if (ImGui::Button("Remove TilemapComponent"))
            selected->RemoveComponent<TilemapComponent>();

        ImGui::Spacing();
    }

    if (auto audio = selected->GetComponent<AudioPlayerComponent>())
    {
        ImGui::SeparatorText("Audio Player");

        uint64_t currentUaid = audio->GetUAID();
        const AssetInfo *asset = AssetManager::GetAssetByID(currentUaid);

        std::string filename = asset ? asset->filename : "(None)";
        ImGui::Text("%s", filename.c_str());

        // Drag & Drop from Asset Browser
        if (ImGui::BeginDragDropTarget())
        {
            if (const ImGuiPayload *payload = ImGui::AcceptDragDropPayload("ASSET_AUDIO"))
            {
                if (payload->DataSize == sizeof(uint64_t))
                {
                    uint64_t newUaid = *(const uint64_t *)payload->Data;
                    audio->SetAudio(newUaid);
                }
            }
            ImGui::EndDragDropTarget();
        }

        // Play/Pause/Stop buttons
        if (ImGui::Button("Play"))
            audio->Play();
        ImGui::SameLine();
        if (ImGui::Button("Pause"))
            audio->Pause();
        ImGui::SameLine();
        if (ImGui::Button("Stop"))
            audio->Stop();

        // Looping
        static bool loop = false;
        loop = ImGui::Checkbox("Loop", &loop);
        audio->SetLooping(loop);

        // Volume
        static float volume = 1.0f;
        if (ImGui::SliderFloat("Volume", &volume, 0.0f, 1.0f))
            audio->SetVolume(volume);

        
        if (ImGui::Button("Remove AudioPlayerComponent"))
            selected->RemoveComponent<AudioPlayerComponent>();
    }

    ImGui::End();
}