-- ============================================================
-- Asylum Compagnon — GearCompassTab.lua
-- Interface de l'onglet Optimisation > GearCompass. Le kit graphique est fourni
-- par UI.lua afin de conserver exactement le style de la fenêtre existante.
-- ============================================================

local _, NS = ...
local unpack = unpack or table.unpack

local GearCompassUI = {}
NS.GearCompassUI = GearCompassUI

function GearCompassUI.Build(parent, kit)
    local Label, MakeButton, MakeCopyBox = kit.Label, kit.MakeButton, kit.MakeCopyBox
    local Solid, Border, COLORS = kit.Solid, kit.Border, kit.COLORS
    local siteURL = kit.URL or "https://gearcompass.turbopigeon.fr"

    local title = Label(parent, 16)
    title:SetPoint("TOPLEFT", 20, -8)
    title:SetText(NS.L("Export GearCompass"))

    local description = Label(parent, 10, COLORS.muted)
    description:SetPoint("TOPLEFT", 20, -30)
    description:SetPoint("TOPRIGHT", -20, -30)
    description:SetJustifyH("LEFT")
    description:SetText(NS.L("Exporte l'équipement porté et les objets des sacs vers l'application GearCompass."))

    local siteLabel = Label(parent, 10, COLORS.muted)
    siteLabel:SetPoint("TOPLEFT", 20, -51)
    siteLabel:SetText(NS.L("Site GearCompass :"))

    local siteContainer = CreateFrame("Frame", nil, parent)
    siteContainer:SetHeight(22)
    siteContainer:SetPoint("TOPLEFT", 20, -67)
    siteContainer:SetPoint("TOPRIGHT", -20, -67)
    local siteBG = Solid(siteContainer)
    siteBG:SetAllPoints()
    siteBG:SetVertexColor(unpack(COLORS.field))
    Border(siteContainer, COLORS.line)
    local siteBox = MakeCopyBox(siteContainer, false)
    siteBox:SetPoint("TOPLEFT", 8, 0)
    siteBox:SetPoint("BOTTOMRIGHT", -8, 0)
    siteBox:SetLockedText(siteURL)
    siteContainer:EnableMouse(true)
    siteContainer:SetScript("OnMouseDown", function() siteBox:SetFocus() end)

    local checkboxes = {}
    local settings = NS.GearCompassDB.GetSettings()
    local definitions = {
        { key = "includeEquipped", label = "Inclure l'équipement porté", x = 20, y = -101 },
        { key = "includeBags", label = "Inclure les sacs", x = 220, y = -101 },
        { key = "includeNonEquippable", label = "Inclure les objets non équipables", x = 20, y = -125 },
    }

    local function MakeCheckbox(definition)
        local button = CreateFrame("Button", nil, parent)
        button:SetSize(250, 20)
        button:SetPoint("TOPLEFT", definition.x, definition.y)
        local box = CreateFrame("Frame", nil, button)
        box:SetSize(16, 16)
        box:SetPoint("LEFT")
        local bg = Solid(box)
        bg:SetAllPoints()
        bg:SetVertexColor(unpack(COLORS.field))
        Border(box, COLORS.line)
        local mark = Solid(box, "ARTWORK")
        mark:SetSize(10, 10)
        mark:SetPoint("CENTER")
        mark:SetVertexColor(unpack(COLORS.accent))
        local label = Label(button, 10)
        label:SetPoint("LEFT", box, "RIGHT", 7, 0)
        label:SetText(NS.L(definition.label))
        button.mark = mark
        button:SetScript("OnClick", function()
            settings[definition.key] = not (settings[definition.key] ~= false)
            mark:SetShown(settings[definition.key] ~= false)
        end)
        checkboxes[#checkboxes + 1] = { definition = definition, button = button }
        return button
    end
    for _, definition in ipairs(definitions) do MakeCheckbox(definition) end

    local generate = MakeButton(parent, NS.L("Générer"), 76, 20)
    generate:SetPoint("TOPLEFT", 20, -153)
    local selectAll = MakeButton(parent, NS.L("Tout sélectionner"), 96, 20)
    selectAll:SetPoint("LEFT", generate, "RIGHT", 6, 0)
    local refresh = MakeButton(parent, NS.L("Actualiser"), 76, 20)
    refresh:SetPoint("LEFT", selectAll, "RIGHT", 6, 0)
    local clear = MakeButton(parent, NS.L("Effacer"), 62, 20)
    clear:SetPoint("LEFT", refresh, "RIGHT", 6, 0)

    local status = Label(parent, 10)
    status:SetPoint("TOPLEFT", 20, -180)
    status:SetPoint("TOPRIGHT", -20, -180)
    status:SetJustifyH("LEFT")

    local textContainer = CreateFrame("Frame", nil, parent)
    textContainer:SetPoint("TOPLEFT", 20, -201)
    textContainer:SetPoint("BOTTOMRIGHT", -20, 12)
    local fieldBG = Solid(textContainer)
    fieldBG:SetAllPoints()
    fieldBG:SetVertexColor(unpack(COLORS.field))
    Border(textContainer, COLORS.line)

    local scroll = CreateFrame("ScrollFrame", nil, textContainer, "UIPanelScrollFrameTemplate")
    scroll:SetPoint("TOPLEFT", 8, -8)
    scroll:SetPoint("BOTTOMRIGHT", -28, 8)
    local textBox = MakeCopyBox(scroll, true)
    textBox:SetWidth(520)
    textBox:SetHeight(100)
    scroll:SetScrollChild(textBox)

    local function ResizeTextBox()
        local width = math.max(100, scroll:GetWidth() or 520)
        textBox:SetWidth(width)
        local stringHeight = textBox.GetStringHeight and textBox:GetStringHeight() or 0
        textBox:SetHeight(math.max(scroll:GetHeight() or 100, stringHeight + 24))
    end
    scroll:SetScript("OnSizeChanged", ResizeTextBox)

    local function SetExport(text)
        textBox:SetLockedText(text or "")
        scroll:SetVerticalScroll(0)
        C_Timer.After(0, ResizeTextBox)
    end

    local function RefreshView()
        settings = NS.GearCompassDB.GetSettings()
        for _, entry in ipairs(checkboxes) do
            entry.button.mark:SetShown(settings[entry.definition.key] ~= false)
        end
        local data = NS.GearCompassDB.Get()
        if data and data.lastExport and textBox.lockedText ~= data.lastExport then SetExport(data.lastExport) end
        local summary = NS.GearCompass.GetLastSummary and NS.GearCompass.GetLastSummary()
        if summary then
            status:SetText((NS.L("Export terminé : %d objets · Équipement : %d · Sacs : %d · Ignorés : %d · Erreurs : %d"))
                :format(summary.total or 0, summary.equipped or 0, summary.bags or 0,
                    summary.excluded or 0, summary.errors or 0))
        elseif data and data.lastExport then
            status:SetText(NS.L("Export précédent chargé."))
        elseif not textBox.lockedText or textBox.lockedText == "" then
            status:SetText(NS.L("Prêt à générer un export."))
        end
    end

    local function GenerateExport()
        status:SetText(NS.L("Scan en cours…"))
        NS.GearCompass.StartExport(function(done, total, phase)
            local label = phase == "gems"
                and NS.L("Chargement des gemmes : %d/%d")
                or NS.L("Chargement des objets : %d/%d")
            status:SetText(label:format(done, total))
        end, function(json, err, summary)
            if not json then
                status:SetText("|cffea4850" .. NS.L("Échec de l'export : ") .. tostring(err or "?") .. "|r")
                return
            end
            SetExport(json)
            status:SetText((NS.L("Export terminé : %d objets · Équipement : %d · Sacs : %d · Ignorés : %d · Erreurs : %d"))
                :format(summary.total, summary.equipped, summary.bags,
                    summary.excluded or 0, summary.errors))
        end)
    end
    generate:SetScript("OnClick", GenerateExport)

    selectAll:SetScript("OnClick", function()
        textBox:SetFocus()
        textBox:HighlightText()
    end)

    refresh:SetScript("OnClick", GenerateExport)

    clear:SetScript("OnClick", function()
        local data = NS.GearCompassDB.Get()
        if data then data.lastExport = nil end
        if NS.GearCompass.ClearLastSummary then NS.GearCompass.ClearLastSummary() end
        SetExport("")
        status:SetText(NS.L("Export effacé."))
    end)

    NS.RefreshGearCompassUI = RefreshView
    RefreshView()
    return { Refresh = RefreshView, SetExport = SetExport }
end
