-- ============================================================
-- Asylum Compagnon — TankgearTab.lua
-- Interface de l'onglet Optimisation > Tankgear. 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 TankgearUI = {}
NS.TankgearUI = TankgearUI

function TankgearUI.Build(parent, kit)
    local Label, MakeButton, MakeCopyBox = kit.Label, kit.MakeButton, kit.MakeCopyBox
    local Solid, Border, COLORS = kit.Solid, kit.Border, kit.COLORS

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

    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 Tankgear."))

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

    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"), 100, 24)
    generate:SetPoint("TOPLEFT", 20, -112)
    local selectAll = MakeButton(parent, NS.L("Tout sélectionner"), 125, 24)
    selectAll:SetPoint("LEFT", generate, "RIGHT", 8, 0)
    local refresh = MakeButton(parent, NS.L("Actualiser"), 100, 24)
    refresh:SetPoint("LEFT", selectAll, "RIGHT", 8, 0)
    local clear = MakeButton(parent, NS.L("Effacer"), 90, 24)
    clear:SetPoint("LEFT", refresh, "RIGHT", 8, 0)

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

    local textContainer = CreateFrame("Frame", nil, parent)
    textContainer:SetPoint("TOPLEFT", 20, -166)
    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.TankgearDB.GetSettings()
        for _, entry in ipairs(checkboxes) do
            entry.button.mark:SetShown(settings[entry.definition.key] ~= false)
        end
        local data = NS.TankgearDB.Get()
        if data and data.lastExport and textBox.lockedText ~= data.lastExport then SetExport(data.lastExport) end
        local summary = NS.Tankgear.GetLastSummary and NS.Tankgear.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.Tankgear.StartExport(function(done, total)
            status:SetText((NS.L("Chargement des objets : %d/%d")):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.TankgearDB.Get()
        if data then data.lastExport = nil end
        if NS.Tankgear.ClearLastSummary then NS.Tankgear.ClearLastSummary() end
        SetExport("")
        status:SetText(NS.L("Export effacé."))
    end)

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