#include "native_ui/tooltip_view.hpp"

#include <algorithm>
#include <format>

namespace poe2::ui {

TooltipLayout TooltipView::BuildLayout(
    const inspector::ItemInspectionReport& report,
    int cursorX,
    int cursorY,
    int screenW,
    int screenH
) {
    TooltipLayout layout;
    layout.hasBrickAlert = report.isBrick;

    // 1. Phân loại màu tiêu đề theo Rarity
    switch (report.rarity) {
        case inspector::ItemRarity::Magic:
            layout.headerColor = colors::BlueMagic;
            break;
        case inspector::ItemRarity::Rare:
            layout.headerColor = colors::YellowRare;
            break;
        case inspector::ItemRarity::Unique:
            layout.headerColor = colors::OrangeUnique;
            break;
        case inspector::ItemRarity::Normal:
        default:
            layout.headerColor = colors::White;
            break;
    }

    if (report.isBrick) {
        layout.borderColor = colors::BrickRed;
        layout.lines.push_back(TooltipLine{
            "=== [CANH BAO: BAN DO BRICK NGUY HIEM] ===",
            colors::BrickRed,
            true,
            false
        });
    }

    // 2. Tiêu đề tên trang bị hoặc loại trang bị
    std::string title = report.itemName.empty() ? std::string(inspector::GetCategoryName(report.category)) : report.itemName;
    layout.lines.push_back(TooltipLine{title, layout.headerColor, true, false});

    if (!report.baseType.empty() && report.baseType != report.itemName) {
        layout.lines.push_back(TooltipLine{report.baseType, colors::GrayText, false, false});
    }

    // 3. Thông số cơ bản
    if (report.itemLevel > 0) {
        layout.lines.push_back(TooltipLine{
            std::format("Item Level: {}", report.itemLevel),
            colors::GrayText,
            false,
            false
        });
    }

    if (report.quality > 0) {
        layout.lines.push_back(TooltipLine{
            std::format("Quality: +{}%", report.quality),
            colors::BlueMagic,
            false,
            false
        });
    }

    if (!report.sockets.empty()) {
        layout.lines.push_back(TooltipLine{
            std::format("Sockets: {}", report.sockets),
            colors::White,
            false,
            false
        });
    }

    // 4. Phân tích Mod Waystone
    if (report.category == inspector::ItemCategory::Waystone) {
        if (!report.redMods.empty()) {
            layout.lines.push_back(TooltipLine{"--- MOD NGUY HIEM CHET NGUOI ---", colors::BrickRed, true, true});
            for (const auto& mod : report.redMods) {
                layout.lines.push_back(TooltipLine{std::format("[X] {}", mod), colors::BrickRed, false, false});
            }
        }

        if (!report.yellowMods.empty()) {
            layout.lines.push_back(TooltipLine{"--- MOD CANH BAO ---", colors::DangerOrange, false, true});
            for (const auto& mod : report.yellowMods) {
                layout.lines.push_back(TooltipLine{std::format("[!] {}", mod), colors::DangerOrange, false, false});
            }
        }

        if (!report.greenMods.empty()) {
            layout.lines.push_back(TooltipLine{"--- MOD PHAN THUONG GIA TRI ---", colors::RewardGreen, false, true});
            for (const auto& mod : report.greenMods) {
                layout.lines.push_back(TooltipLine{std::format("[+] {}", mod), colors::RewardGreen, false, false});
            }
        }
    } else {
        // 5. Trang bị thường / Vũ khí / Giáp: Phân tích Open Affixes
        if (report.maxPrefixes > 0 || report.maxSuffixes > 0) {
            layout.lines.push_back(TooltipLine{"--- KHOANG TRONG AFFIX (CRAFTING) ---", colors::GoldBorder, true, true});

            int usedP = report.maxPrefixes - report.openPrefixes;
            Color pColor = report.openPrefixes > 0 ? colors::RewardGreen : colors::SubduedText;
            layout.lines.push_back(TooltipLine{
                std::format("Prefixes: {}/{} (con {} vi tri trong)", usedP, report.maxPrefixes, report.openPrefixes),
                pColor,
                false,
                false
            });

            int usedS = report.maxSuffixes - report.openSuffixes;
            Color sColor = report.openSuffixes > 0 ? colors::RewardGreen : colors::SubduedText;
            layout.lines.push_back(TooltipLine{
                std::format("Suffixes: {}/{} (con {} vi tri trong)", usedS, report.maxSuffixes, report.openSuffixes),
                sColor,
                false,
                false
            });
        }
    }

    // 6. Tính toán kích thước hộp Bounding Box và vị trí chống tràn màn hình
    size_t maxLineLen = 30;
    for (const auto& l : layout.lines) {
        maxLineLen = std::max(maxLineLen, l.text.size());
    }

    int boxWidth = static_cast<int>(std::clamp(maxLineLen * 8 + 30, size_t{340}, size_t{560}));
    int boxHeight = static_cast<int>(layout.lines.size() * 22 + 24);

    int posX = cursorX + 24;
    int posY = cursorY + 12;

    if (screenW > 0 && posX + boxWidth > screenW - 10) {
        posX = cursorX - boxWidth - 16;
    }
    if (posX < 10) posX = 10;

    if (screenH > 0 && posY + boxHeight > screenH - 10) {
        posY = screenH - boxHeight - 10;
    }
    if (posY < 10) posY = 10;

    layout.bounds = Rect{posX, posY, boxWidth, boxHeight};
    return layout;
}

} // namespace poe2::ui
