--[[
============================================================================
OutfitOptions.lua  (added in v14.2.0)
============================================================================

Per-outfit settings dialog. Covers:
  4.2 Per-Outfit Ignore-Slot Flags  — checkboxes per slot
  4.3 Outfit Icon Picker            — grid of curated WoW icons

Triggered by right-clicking a saved outfit list entry. Ignored slots are
respected by Outfits:Load — slots flagged as ignored are NOT applied to the
preview model, so the player's currently-equipped item in that slot stays.

Why a separate module:
  - It owns one clearly-bounded UI surface (the options dialog frame).
  - Two distinct features (ignore flags + icon picker) compose into one
    coherent dialog. Putting them in Outfits.lua would muddle a file that
    is already 600+ lines.
  - Future per-outfit settings (notes, color tags, skin previews) all
    naturally hang off the same dialog.
============================================================================
]]--
local ADDON_NAME, NS = ...
local ETB = NS.ETB
NS.ETB.OutfitOptions = NS.ETB.OutfitOptions or {}
local OO = NS.ETB.OutfitOptions

-- Stable WoW slot names used in saved outfit `items` keys.
-- Order chosen to match retail wardrobe layout (top-down, left then right).
local SLOT_DISPLAY_ORDER = {
    "Head", "Shoulder", "Chest", "Wrist", "Hands", "Waist",
    "Legs", "Feet", "Back", "Shirt", "Tabard", "MainHand", "OffHand",
}

-- Curated icon set for the picker. Mostly armor + utility icons that read
-- well at 32x32. Users can also paste a custom icon path via the textbox.
local ICON_PRESETS = {
    "Interface\\Icons\\INV_Chest_Cloth_17",
    "Interface\\Icons\\INV_Chest_Leather_07",
    "Interface\\Icons\\INV_Chest_Mail_03",
    "Interface\\Icons\\INV_Chest_Plate03",
    "Interface\\Icons\\INV_Helmet_29",
    "Interface\\Icons\\INV_Shoulder_25",
    "Interface\\Icons\\INV_Pants_Plate_24",
    "Interface\\Icons\\INV_Boots_Plate_05",
    "Interface\\Icons\\INV_Gauntlets_25",
    "Interface\\Icons\\INV_Misc_Cape_18",
    "Interface\\Icons\\INV_Sword_48",
    "Interface\\Icons\\INV_Hammer_24",
    "Interface\\Icons\\INV_Axe_64",
    "Interface\\Icons\\INV_Staff_30",
    "Interface\\Icons\\INV_Misc_Bag_10",
    "Interface\\Icons\\INV_Misc_Crown_01",
    "Interface\\Icons\\INV_Misc_Bell_01",
    "Interface\\Icons\\Spell_Holy_DivineProtection",
    "Interface\\Icons\\Spell_Shadow_DemonicFortitude",
    "Interface\\Icons\\Achievement_Boss_Ragnaros",
    "Interface\\Icons\\Achievement_Boss_LichKing",
    "Interface\\Icons\\Achievement_Boss_Deathwing_Nef",
    "Interface\\Icons\\Achievement_Boss_Garrosh",
    "Interface\\Icons\\Inv_helmet_103",
}

-- =============================================================================
-- DIALOG
-- =============================================================================

function OO:Show(outfitID, isAccount)
    if not self.frame then self:CreateFrame() end
    self.outfitID = outfitID
    self.isAccount = isAccount

    local outfit = self:GetOutfit()
    if not outfit then return end

    self.frame.title:SetText("|cffffd100" .. (outfit.name or "Outfit") .. "|r — Options")

    self:RefreshSlotChecks()
    self:RefreshIconGrid()

    self.frame:Show()
end

function OO:Hide()
    if self.frame then self.frame:Hide() end
end

function OO:GetOutfit()
    if not self.outfitID then return nil end
    if self.isAccount then
        local pm = ETB.TransmogUI and ETB.TransmogUI.ProfileManager
        return pm and pm.accountOutfits and pm.accountOutfits[self.outfitID] or nil
    else
        return _G.ETBTUI_SavedOutfits and _G.ETBTUI_SavedOutfits[self.outfitID] or nil
    end
end

function OO:CreateFrame()
    local f = CreateFrame("Frame", nil, UIParent, "BackdropTemplate")
    f:SetSize(360, 440)
    f:SetPoint("CENTER")
    f:SetFrameStrata("DIALOG")
    f:SetBackdrop({
        bgFile = "Interface\\DialogFrame\\UI-DialogBox-Background-Dark",
        edgeFile = "Interface\\Tooltips\\UI-Tooltip-Border",
        tile = true, tileSize = 16, edgeSize = 16,
        insets = { left = 4, right = 4, top = 4, bottom = 4 },
    })
    f:EnableMouse(true)
    f:SetMovable(true)
    f:RegisterForDrag("LeftButton")
    f:SetScript("OnDragStart", f.StartMoving)
    f:SetScript("OnDragStop", f.StopMovingOrSizing)
    f:Hide()

    f.title = f:CreateFontString(nil, "OVERLAY", "GameFontNormalLarge")
    f.title:SetPoint("TOP", 0, -10)

    local closeBtn = CreateFrame("Button", nil, f, "UIPanelCloseButton")
    closeBtn:SetPoint("TOPRIGHT", -4, -4)
    closeBtn:SetScript("OnClick", function() OO:Hide() end)

    -- Section: ignored slots (Feature 4.2)
    f.slotsHeader = f:CreateFontString(nil, "OVERLAY", "GameFontNormal")
    f.slotsHeader:SetPoint("TOPLEFT", 14, -38)
    f.slotsHeader:SetText("|cffffd100Ignore slots when loading:|r")

    f.slotChecks = {}
    -- Lay out as 3 columns × 5 rows (13 slots so last row partial).
    -- Row 1 starts at y=-58, each row is 18 high. Column step 110.
    local startY = -58
    local rowH = 18
    local colW = 110
    for i, slotName in ipairs(SLOT_DISPLAY_ORDER) do
        local col = (i - 1) % 3
        local row = math.floor((i - 1) / 3)
        local cb = CreateFrame("CheckButton", nil, f, "UICheckButtonTemplate")
        cb:SetSize(18, 18)
        cb:SetPoint("TOPLEFT", 14 + col * colW, startY - row * rowH)
        cb.slotName = slotName

        local txt = cb:CreateFontString(nil, "OVERLAY", "GameFontNormalSmall")
        txt:SetPoint("LEFT", cb, "RIGHT", 1, 1)
        txt:SetText(slotName)

        cb:SetScript("OnClick", function(self)
            OO:OnSlotToggle(self.slotName, self:GetChecked())
        end)
        f.slotChecks[slotName] = cb
    end

    -- Section: icon picker (Feature 4.3)
    f.iconHeader = f:CreateFontString(nil, "OVERLAY", "GameFontNormal")
    f.iconHeader:SetPoint("TOPLEFT", 14, -180)
    f.iconHeader:SetText("|cffffd100Outfit icon:|r")

    -- Show currently-selected icon as a large preview at the right of header
    f.currentIcon = f:CreateTexture(nil, "ARTWORK")
    f.currentIcon:SetSize(36, 36)
    f.currentIcon:SetPoint("TOPLEFT", 90, -176)
    f.currentIcon:SetTexCoord(0.08, 0.92, 0.08, 0.92)

    f.iconButtons = {}
    local IPR = 6  -- icons per row
    for i, path in ipairs(ICON_PRESETS) do
        local col = (i - 1) % IPR
        local row = math.floor((i - 1) / IPR)
        local b = CreateFrame("Button", nil, f)
        b:SetSize(34, 34)
        b:SetPoint("TOPLEFT", 14 + col * 38, -224 - row * 38)

        local tex = b:CreateTexture(nil, "ARTWORK")
        tex:SetAllPoints()
        tex:SetTexCoord(0.08, 0.92, 0.08, 0.92)
        tex:SetTexture(path)

        local highlight = b:CreateTexture(nil, "HIGHLIGHT")
        highlight:SetAllPoints()
        highlight:SetColorTexture(1, 1, 1, 0.3)

        local selectedBorder = b:CreateTexture(nil, "OVERLAY")
        selectedBorder:SetAllPoints()
        selectedBorder:SetColorTexture(1, 0.82, 0, 0)
        b.selectedBorder = selectedBorder

        b.iconPath = path
        b:SetScript("OnClick", function(self) OO:SelectIcon(self.iconPath) end)
        f.iconButtons[i] = b
    end

    f.frame = f
    self.frame = f
end

-- =============================================================================
-- INTERACTIONS
-- =============================================================================

function OO:OnSlotToggle(slotName, isChecked)
    local outfit = self:GetOutfit()
    if not outfit then return end
    outfit.ignoredSlots = outfit.ignoredSlots or {}
    if isChecked then
        outfit.ignoredSlots[slotName] = true
    else
        outfit.ignoredSlots[slotName] = nil
    end
end

function OO:SelectIcon(iconPath)
    local outfit = self:GetOutfit()
    if not outfit then return end
    outfit.icon = iconPath
    if self.frame and self.frame.currentIcon then
        self.frame.currentIcon:SetTexture(iconPath)
    end
    -- Visual feedback: dim all borders, highlight the chosen one
    if self.frame and self.frame.iconButtons then
        for _, btn in ipairs(self.frame.iconButtons) do
            btn.selectedBorder:SetColorTexture(1, 0.82, 0,
                btn.iconPath == iconPath and 0.5 or 0)
        end
    end
    -- Refresh the outfit list so the new icon shows in the row
    if ETB.TransmogUI and ETB.TransmogUI.Outfits then
        ETB.TransmogUI.Outfits:Refresh(ETB.TransmogUI)
    end
end

-- =============================================================================
-- REFRESH
-- =============================================================================

function OO:RefreshSlotChecks()
    local outfit = self:GetOutfit()
    if not outfit or not self.frame then return end
    local ignored = outfit.ignoredSlots or {}
    for slotName, cb in pairs(self.frame.slotChecks) do
        cb:SetChecked(ignored[slotName] == true)
    end
end

function OO:RefreshIconGrid()
    local outfit = self:GetOutfit()
    if not outfit or not self.frame then return end
    local current = outfit.icon or "Interface\\Icons\\INV_Chest_Cloth_17"
    self.frame.currentIcon:SetTexture(current)
    for _, btn in ipairs(self.frame.iconButtons) do
        btn.selectedBorder:SetColorTexture(1, 0.82, 0,
            btn.iconPath == current and 0.5 or 0)
    end
end
