local _, privateDB = ...

-- ============================================================================
-- CRAFT CONFIRMATION DIALOG
-- Lazy-built modal for the [Craft] button on queue rows.
-- Extracted from HDG_RecipesTab.lua during the v2.42.x code-smell sweep.
-- ============================================================================

local CONFIG = privateDB.CONFIG
local L = HDG_L or {}
local HDG = _G.HousingDecorGuide

local HDG_CraftDialog = {}
privateDB.HDG_CraftDialog = HDG_CraftDialog

local function GetScheme() return HDG.Theme.GetCurrentScheme() end
local function RegisterWidget(w, t) HDG.Theme.RegisterWidget(w, t) end
local function ApplyFont(fs, s, ft) HDG.Theme.ApplyFont(fs, s, ft) end

local function Data() return HDG_UIHelpers.Data() end

local craftConfirmFrame = nil

-- Create the craft confirmation dialog frame (lazy-init, called once)
local function CreateCraftDialog()
    craftConfirmFrame = CreateFrame("Frame", "HDG_CraftConfirmDialog", UIParent, "BackdropTemplate")
    craftConfirmFrame:SetSize(380, 165)
    craftConfirmFrame:SetPoint("CENTER", 0, 100)
    craftConfirmFrame:SetFrameStrata("DIALOG")
    craftConfirmFrame:SetBackdrop({
        bgFile = CONFIG.TEXTURES.WHITE_BG,
        edgeFile = CONFIG.TEXTURES.WHITE_BG,
        tile = false,
        edgeSize = 2,
        insets = { left = 0, right = 0, top = 0, bottom = 0 }
    })
    local cfScheme = GetScheme()
    craftConfirmFrame:SetBackdropColor(cfScheme.bg.r, cfScheme.bg.g, cfScheme.bg.b, 0.95)
    craftConfirmFrame:SetBackdropBorderColor(cfScheme.accent.r, cfScheme.accent.g, cfScheme.accent.b, 1)
    craftConfirmFrame._accentBorder = true
    RegisterWidget(craftConfirmFrame, "Frame")
    craftConfirmFrame:EnableMouse(true)
    craftConfirmFrame:SetMovable(true)
    craftConfirmFrame:RegisterForDrag("LeftButton")
    craftConfirmFrame:SetScript("OnDragStart", craftConfirmFrame.StartMoving)
    craftConfirmFrame:SetScript("OnDragStop", craftConfirmFrame.StopMovingOrSizing)

    local title = craftConfirmFrame:CreateFontString(nil, "OVERLAY", "GameFontNormal")
    title:SetPoint("TOP", 0, -12)
    ApplyFont(title, cfScheme, "header")
    title:SetText(HDG.Theme.C_Accent() .. L["RECIPE_CRAFT_CONFIRM"] .. "|r")
    craftConfirmFrame.title = title

    local itemText = craftConfirmFrame:CreateFontString(nil, "OVERLAY", "GameFontNormal")
    itemText:SetPoint("TOP", 0, -40)
    itemText:SetWidth(360)
    ApplyFont(itemText, cfScheme, "body")
    craftConfirmFrame.itemText = itemText

    local infoText = craftConfirmFrame:CreateFontString(nil, "OVERLAY", "GameFontNormal")
    infoText:SetPoint("TOP", 0, -62)
    infoText:SetWidth(360)
    if cfScheme then
        infoText:SetTextColor(cfScheme.text_dim.r, cfScheme.text_dim.g, cfScheme.text_dim.b, cfScheme.text_dim.a)
    end
    ApplyFont(infoText, cfScheme, "small")
    craftConfirmFrame.infoText = infoText

    local apiNote = craftConfirmFrame:CreateFontString(nil, "OVERLAY", "GameFontNormal")
    apiNote:SetPoint("TOP", 0, -80)
    apiNote:SetWidth(360)
    if cfScheme then
        apiNote:SetTextColor(cfScheme.text_dim.r * 0.7, cfScheme.text_dim.g * 0.7, cfScheme.text_dim.b * 0.7, cfScheme.text_dim.a)
    end
    ApplyFont(apiNote, cfScheme, "small")
    apiNote:SetText(L["RECIPE_API_NOTE"])
    craftConfirmFrame.apiNote = apiNote

    local function CreateStyledButton(parent, width, color, hoverColor)
        local btn = CreateFrame("Button", nil, parent, "BackdropTemplate")
        btn:SetSize(width, 28)
        btn:SetBackdrop({
            bgFile = CONFIG.TEXTURES.WHITE_BG,
            edgeFile = CONFIG.TEXTURES.WHITE_BG,
            tile = false,
            edgeSize = 1,
        })
        btn:SetBackdropColor(unpack(color))
        btn:SetBackdropBorderColor(color[1] + 0.1, color[2] + 0.1, color[3] + 0.1, 1)

        local btnText = btn:CreateFontString(nil, "OVERLAY", "GameFontNormal")
        btnText:SetPoint("CENTER", 0, 0)
        ApplyFont(btnText, GetScheme(), "body")
        btn.text = btnText

        btn:SetScript("OnEnter", function(self) self:SetBackdropColor(unpack(hoverColor)) end)
        btn:SetScript("OnLeave", function(self) self:SetBackdropColor(unpack(color)) end)
        return btn
    end

    -- Layout: [Craft N] [-] [+] [Craft Max] [Cancel]
    local craftBtn = CreateStyledButton(craftConfirmFrame, 70, { 0.15, 0.7, 0.15, 1 }, { 0.2, 0.85, 0.2, 1 })
    craftBtn:SetPoint("BOTTOMLEFT", 12, 15)
    craftBtn.text:SetText(HDG.Theme.C_Text() .. L["RECIPE_CRAFT_ONE"] .. "|r")
    craftConfirmFrame.craftBtn = craftBtn

    local minusBtn = CreateStyledButton(craftConfirmFrame, 28, { 0.6, 0.35, 0.1, 1 }, { 0.75, 0.45, 0.15, 1 })
    minusBtn:SetPoint("LEFT", craftBtn, "RIGHT", 6, 0)
    minusBtn.text:SetText(HDG.Theme.C_Text() .. "-|r")
    craftConfirmFrame.minusBtn = minusBtn

    local plusBtn = CreateStyledButton(craftConfirmFrame, 28, { 0.6, 0.35, 0.1, 1 }, { 0.75, 0.45, 0.15, 1 })
    plusBtn:SetPoint("LEFT", minusBtn, "RIGHT", 4, 0)
    plusBtn.text:SetText(HDG.Theme.C_Text() .. "+|r")
    craftConfirmFrame.plusBtn = plusBtn

    local craftMaxBtn = CreateStyledButton(craftConfirmFrame, 70, { 0.08, 0.45, 0.40, 1 }, { 0.12, 0.55, 0.50, 1 })
    craftMaxBtn:SetPoint("LEFT", plusBtn, "RIGHT", 6, 0)
    craftConfirmFrame.craftMaxBtn = craftMaxBtn

    local cancelBtn = CreateStyledButton(craftConfirmFrame, 60, { 0.25, 0.25, 0.25, 1 }, { 0.35, 0.35, 0.35, 1 })
    cancelBtn:SetPoint("BOTTOMRIGHT", -12, 15)
    cancelBtn.text:SetText(HDG.Theme.C_Text() .. "Cancel|r")
    cancelBtn:SetScript("OnClick", function() craftConfirmFrame:Hide() end)

    craftConfirmFrame:SetScript("OnKeyDown", function(self, key)
        if key == "ESCAPE" then
            self:SetPropagateKeyboardInput(false)
            self:Hide()
        else
            self:SetPropagateKeyboardInput(true)
        end
    end)

    local keepOpenCheck = CreateFrame("CheckButton", nil, craftConfirmFrame, "UICheckButtonTemplate")
    keepOpenCheck:SetSize(24, 24)
    keepOpenCheck:SetPoint("TOPLEFT", 12, -95)
    keepOpenCheck:SetChecked(not HDG.Store:GetConfig("closeProfWindowAfterCraft"))
    keepOpenCheck:SetScript("OnClick", function(self)
        HDG.Store:Dispatch("SET_CONFIG", { key = "closeProfWindowAfterCraft", value = not self:GetChecked() })
    end)
    craftConfirmFrame.keepOpenCheck = keepOpenCheck

    local koScheme = GetScheme()
    local keepOpenLabel = craftConfirmFrame:CreateFontString(nil, "OVERLAY", "GameFontNormal")
    keepOpenLabel:SetPoint("LEFT", keepOpenCheck, "RIGHT", 2, 0)
    keepOpenLabel:SetText(L["RECIPE_KEEP_PROF_OPEN"])
    if koScheme then
        keepOpenLabel:SetTextColor(koScheme.text_dim.r, koScheme.text_dim.g, koScheme.text_dim.b, koScheme.text_dim.a)
    end
    ApplyFont(keepOpenLabel, koScheme, "small")

    craftConfirmFrame:Hide()
end

-- Show craft confirmation dialog
function HDG_CraftDialog.Show(item, queueIndex)
    if not item or not item.spellID then return end

    local queuedQty = item.quantity or 1
    local _, maxCraftable = HDG_Data.CanCraftRecipe(item)
    maxCraftable = maxCraftable or 0
    local totalQty = math.min(queuedQty, maxCraftable)
    if totalQty <= 0 then totalQty = 1 end

    if not craftConfirmFrame then
        CreateCraftDialog()
    end

    craftConfirmFrame.keepOpenCheck:SetChecked(not HDG.Store:GetConfig("closeProfWindowAfterCraft"))
    craftConfirmFrame.selectedQty = 1
    craftConfirmFrame.maxQty = totalQty

    local function UpdateCraftBtnText()
        craftConfirmFrame.craftBtn.text:SetText(string.format(HDG.Theme.C_Text() .. L["RECIPE_CRAFT_N"] .. "|r", craftConfirmFrame.selectedQty))
    end

    local localizedItemName = Data().GetLocalizedName(item.itemID, item.name)
    craftConfirmFrame.itemText:SetText(string.format(HDG.Theme.C_Text() .. "%s|r", localizedItemName))
    if maxCraftable > 1 then
        local infoStr = string.format("Queued: %d | Can craft: " .. HDG.Theme.C_Success() .. "%d|r", queuedQty, maxCraftable)
        craftConfirmFrame.infoText:SetText(infoStr)
        craftConfirmFrame.craftMaxBtn.text:SetText(string.format(HDG.Theme.C_Text() .. L["RECIPE_CRAFT_MAX"] .. "|r", maxCraftable))
        craftConfirmFrame.craftMaxBtn:Show()
        craftConfirmFrame.minusBtn:Show()
        craftConfirmFrame.plusBtn:Show()
        craftConfirmFrame.maxQty = maxCraftable
    else
        craftConfirmFrame.infoText:SetText(L["RECIPE_CRAFT_QUESTION"])
        craftConfirmFrame.craftMaxBtn:Hide()
        craftConfirmFrame.minusBtn:Hide()
        craftConfirmFrame.plusBtn:Hide()
        craftConfirmFrame.maxQty = 1
    end

    craftConfirmFrame.currentItem = item
    craftConfirmFrame.currentIndex = queueIndex

    craftConfirmFrame.selectedQty = 1
    UpdateCraftBtnText()

    craftConfirmFrame.craftBtn:SetScript("OnClick", function()
        HDG_CraftDialog.Execute(item, queueIndex, craftConfirmFrame.selectedQty)
        craftConfirmFrame:Hide()
    end)

    craftConfirmFrame.minusBtn:SetScript("OnClick", function()
        if craftConfirmFrame.selectedQty > 1 then
            craftConfirmFrame.selectedQty = craftConfirmFrame.selectedQty - 1
            UpdateCraftBtnText()
        end
    end)

    craftConfirmFrame.plusBtn:SetScript("OnClick", function()
        if craftConfirmFrame.selectedQty < craftConfirmFrame.maxQty then
            craftConfirmFrame.selectedQty = craftConfirmFrame.selectedQty + 1
            UpdateCraftBtnText()
        end
    end)

    craftConfirmFrame.craftMaxBtn:SetScript("OnClick", function()
        HDG_CraftDialog.Execute(item, queueIndex, craftConfirmFrame.maxQty)
        craftConfirmFrame:Hide()
    end)

    craftConfirmFrame:Show()
end

-- Execute the actual crafting. Profession window must already be open.
function HDG_CraftDialog.Execute(item, queueIndex, quantity)
    if not item or not item.spellID then
        print(HDG.Theme.C_Error() .. L["RECIPE_MSG_INVALID"])
        return
    end

    quantity = quantity or 1
    local recipeID = item.spellID

    if not C_TradeSkillUI then
        print(HDG.Theme.C_Error() .. L["RECIPE_MSG_NO_API"])
        return
    end

    local isTradeSkillOpen = C_TradeSkillUI.IsTradeSkillReady and C_TradeSkillUI.IsTradeSkillReady()
    if not isTradeSkillOpen then
        print(HDG.Theme.C_Warning() .. L["RECIPE_MSG_PROF_NOT_READY"])
        return
    end

    -- Tell the crafted-result event handler how many crafts to expect before closing the prof window
    if privateDB.pendingCraftInfo then
        privateDB.pendingCraftInfo.itemID = item.itemID
        privateDB.pendingCraftInfo.remaining = quantity
    end

    local success, err = pcall(function()
        C_TradeSkillUI.CraftRecipe(recipeID, quantity, {})
    end)
    if success then
        local localizedCraftName = HDG_UIHelpers.Data().GetLocalizedName(item.itemID, item.name)
        print(string.format(HDG.Theme.C_Accent() .. L["RECIPE_MSG_CRAFTING"], quantity, localizedCraftName))
    else
        print(string.format(HDG.Theme.C_Error() .. L["RECIPE_MSG_CRAFT_FAILED"], tostring(err)))
        if privateDB.pendingCraftInfo then
            privateDB.pendingCraftInfo.itemID = nil
            privateDB.pendingCraftInfo.remaining = 0
        end
    end
end
