local _, ns = ...

------------------------------------------------------------
-- L'ura Memory-Game Helper — Raid Tools tab UI.
-- Built lazily the first time the "L'ura" tab is shown.
------------------------------------------------------------

ns.Lura = ns.Lura or {}
ns.Lura.UI = ns.Lura.UI or {}
local UI = ns.Lura.UI

local PAD_X = 14
local BUTTON_HEIGHT = 20
local ROW_H = 26

------------------------------------------------------------
-- Widget helpers (scoped to this tab)
------------------------------------------------------------

local function StyleButton(btn)
    btn:SetBackdrop({
        bgFile   = "Interface\\Buttons\\WHITE8x8",
        edgeFile = "Interface\\Tooltips\\UI-Tooltip-Border",
        edgeSize = 10,
        insets   = { left = 2, right = 2, top = 2, bottom = 2 },
    })
    btn:SetBackdropColor(0.12, 0.12, 0.12, 0.9)
    btn:SetBackdropBorderColor(0.35, 0.35, 0.35, 0.8)
    if ns.SmoothFrame then ns.SmoothFrame(btn) end
end

local function MakeButton(parent, label, width, onClick)
    local btn = CreateFrame("Button", nil, parent, "BackdropTemplate")
    btn:SetSize(width, BUTTON_HEIGHT)
    StyleButton(btn)
    local fs = btn:CreateFontString(nil, "OVERLAY", "GameFontNormalSmall")
    fs:SetPoint("CENTER", 0, 0)
    fs:SetText(label)
    btn.label = fs
    btn:SetScript("OnEnter", function(self)
        self:SetBackdropBorderColor(0.6, 0.85, 1.0, 1)
    end)
    btn:SetScript("OnLeave", function(self)
        self:SetBackdropBorderColor(0.35, 0.35, 0.35, 0.8)
    end)
    if onClick then btn:SetScript("OnClick", onClick) end
    return btn
end

local function MakeCheckbox(parent, label, getFn, setFn)
    local cb = CreateFrame("CheckButton", nil, parent, "UICheckButtonTemplate")
    cb:SetSize(22, 22)
    cb.Text:SetText(label)
    cb.Text:SetTextColor(unpack(ns.COLORS.TEXT_PRIMARY))
    cb:SetScript("OnClick", function(self)
        if setFn then setFn(self:GetChecked() and true or false) end
    end)
    cb.Refresh = function() cb:SetChecked(getFn() and true or false) end
    cb:Refresh()
    return cb
end

local function MakeSectionHeader(parent, text)
    local fs = parent:CreateFontString(nil, "OVERLAY", "GameFontNormal")
    fs:SetText(text)
    fs:SetTextColor(unpack(ns.COLORS.TEXT_HEADER))
    ns.ApplyTextShadow(fs)
    return fs
end

local function MakeDivider(parent)
    local tex = parent:CreateTexture(nil, "ARTWORK")
    tex:SetHeight(1)
    tex:SetColorTexture(0.3, 0.3, 0.3, 0.7)
    return tex
end

local function MakeBodyText(parent, text)
    local fs = parent:CreateFontString(nil, "OVERLAY", "GameFontNormalSmall")
    fs:SetText(text)
    fs:SetTextColor(unpack(ns.COLORS.TEXT_SECONDARY))
    fs:SetJustifyH("LEFT")
    return fs
end

------------------------------------------------------------
-- Reference table rows
------------------------------------------------------------

local COL_NUM   = 12
local COL_ICON  = 40
local COL_CODE  = 96
local COL_MACRO = 158

local function MakeReferenceRow(parent, entry)
    local row = CreateFrame("Frame", nil, parent)
    row:SetHeight(ROW_H)

    local num = row:CreateFontString(nil, "OVERLAY", "GameFontNormal")
    num:SetPoint("LEFT", row, "LEFT", COL_NUM, 0)
    num:SetText(tostring(entry.slot))
    num:SetTextColor(1, 1, 0.3, 1)

    local iconBg = row:CreateTexture(nil, "BACKGROUND")
    iconBg:SetSize(22, 22)
    iconBg:SetPoint("LEFT", row, "LEFT", COL_ICON, 0)
    iconBg:SetColorTexture(0, 0, 0, 0.55)

    local icon = row:CreateTexture(nil, "ARTWORK")
    icon:SetSize(20, 20)
    icon:SetPoint("CENTER", iconBg, "CENTER", 0, 0)
    icon:SetTexture(entry.texture)

    local code = row:CreateFontString(nil, "OVERLAY", "GameFontNormalSmall")
    code:SetPoint("LEFT", row, "LEFT", COL_CODE, 0)
    code:SetText(entry.label or entry.code or "")
    code:SetTextColor(unpack(ns.COLORS.TEXT_PRIMARY))

    local mname = row:CreateFontString(nil, "OVERLAY", "GameFontNormalSmall")
    mname:SetPoint("LEFT", row, "LEFT", COL_MACRO, 0)
    mname:SetText(entry.macroName)
    mname:SetTextColor(unpack(ns.COLORS.TEXT_SECONDARY))

    return row
end

------------------------------------------------------------
-- Build
------------------------------------------------------------

local built = false
local refreshers = {}

function UI:BuildInto(parentContainer)
    if built then return end
    built = true
    local L = ns.Lura

    -- Scroll frame so content can breathe even if we add rows later.
    local scroll = CreateFrame("ScrollFrame", nil, parentContainer, "UIPanelScrollFrameTemplate")
    scroll:SetPoint("TOPLEFT", 0, 0)
    scroll:SetPoint("BOTTOMRIGHT", -24, 6)
    local parent = CreateFrame("Frame", nil, scroll)
    parent:SetSize(1, 1)  -- width set below once we know the parent container width
    scroll:SetScrollChild(parent)

    parentContainer:HookScript("OnSizeChanged", function(self, w, h)
        parent:SetWidth(math.max(w - 24, 200))
    end)
    local pw = parentContainer:GetWidth()
    if pw and pw > 0 then parent:SetWidth(math.max(pw - 24, 200)) end

    -- Title
    local title = parent:CreateFontString(nil, "OVERLAY", "GameFontNormalLarge")
    title:SetPoint("TOPLEFT", PAD_X, -10)
    title:SetText("L'ura Memory-Game Helper")
    title:SetTextColor(unpack(ns.COLORS.ACCENT_GOLD))
    ns.ApplyTextShadow(title)

    local desc = MakeBodyText(parent,
        "Pentagon display driven by |cffffffff/raid|r chat. Raid leader presses the\n"
        .. "|cffffffffYY_Lura_1..5|r macros; every YippYapp client renders the runes live.\n"
        .. "Each macro broadcasts its symbol's texture path directly — no /reload\n"
        .. "required on other clients, no |cffffffffInterface\\ICONS\\|r file install.")
    desc:SetPoint("TOPLEFT", title, "BOTTOMLEFT", 0, -4)
    desc:SetPoint("RIGHT", parent, "RIGHT", -PAD_X, 0)

    -- Enable + actions
    local enableCB = MakeCheckbox(parent, "Enabled",
        function() return L:IsEnabled() end,
        function(v) L:SetEnabled(v) end)
    enableCB:SetPoint("TOPLEFT", desc, "BOTTOMLEFT", -4, -6)
    table.insert(refreshers, enableCB.Refresh)

    local strictCB = MakeCheckbox(parent, "Only listen during L'ura encounter",
        function() return L:IsRestrictedToEncounter() end,
        function(v) L:SetRestrictedToEncounter(v) end)
    strictCB:SetPoint("TOPLEFT", enableCB, "BOTTOMLEFT", 0, -2)
    table.insert(refreshers, strictCB.Refresh)

    local strictHint = MakeBodyText(parent,
        "If the pentagon doesn't fill live, try unchecking this — the listener\n"
        .. "then stays armed whenever enabled. Safe because you're only firing\n"
        .. "the macros on the boss anyway.")
    strictHint:SetPoint("TOPLEFT", strictCB, "BOTTOMLEFT", 4, -2)
    strictHint:SetPoint("RIGHT", parent, "RIGHT", -PAD_X, 0)

    local previewBtn = MakeButton(parent, "Preview", 70, function() L:Preview() end)
    previewBtn:SetPoint("TOPLEFT", strictHint, "BOTTOMLEFT", -4, -6)

    local testBtn = MakeButton(parent, "Simulate", 72, function() L:Test() end)
    testBtn:SetPoint("LEFT", previewBtn, "RIGHT", 6, 0)

    local clearBtn = MakeButton(parent, "Clear", 58, function() L:Clear() end)
    clearBtn:SetPoint("LEFT", testBtn, "RIGHT", 6, 0)

    -- Mover
    local unlockBtn = MakeButton(parent, "Unlock to move", 110, function()
        L:SetLocked(false)
    end)
    unlockBtn:SetPoint("TOPLEFT", previewBtn, "BOTTOMLEFT", 0, -6)

    local lockBtn = MakeButton(parent, "Lock", 52, function()
        L:SetLocked(true)
        L:Clear()
    end)
    lockBtn:SetPoint("LEFT", unlockBtn, "RIGHT", 6, 0)

    local moverHint = MakeBodyText(parent,
        "Unlock shows the pentagon; drag it where you want it, then Lock.")
    moverHint:SetPoint("TOPLEFT", unlockBtn, "BOTTOMLEFT", -4, -4)
    moverHint:SetPoint("RIGHT", parent, "RIGHT", -PAD_X, 0)

    -- Macros section
    local macrosHeader = MakeSectionHeader(parent, "Raid Leader Macros")
    macrosHeader:SetPoint("TOPLEFT", moverHint, "BOTTOMLEFT", 4, -10)
    local macrosDivider = MakeDivider(parent)
    macrosDivider:SetPoint("LEFT", macrosHeader, "RIGHT", 8, 0)
    macrosDivider:SetPoint("RIGHT", parent, "RIGHT", -PAD_X, 0)

    local createBtn = MakeButton(parent, "Create / refresh macros", 170, function()
        L:CreateMacros()
    end)
    createBtn:SetPoint("TOPLEFT", macrosHeader, "BOTTOMLEFT", 0, -6)

    local macrosBody = MakeBodyText(parent,
        "Creates |cffffffffYY_Lura_1..5|r with a |cff888888?|r icon and a /raid body.\n"
        .. "The pentagon always uses our bundled textures — no file install needed\n"
        .. "on any client.")
    macrosBody:SetPoint("TOPLEFT", createBtn, "BOTTOMLEFT", 0, -4)
    macrosBody:SetPoint("RIGHT", parent, "RIGHT", -PAD_X, 0)

    -- Reference table header
    local tableHeader = parent:CreateFontString(nil, "OVERLAY", "GameFontNormalSmall")
    tableHeader:SetPoint("TOPLEFT", macrosBody, "BOTTOMLEFT", 0, -6)
    tableHeader:SetText("|cff888888  #   Symbol    Name      Macro name|r")

    -- Reference table rows, chained vertically
    local ref = L:GetReference()
    local prev = tableHeader
    local firstRow
    for i, entry in ipairs(ref) do
        local row = MakeReferenceRow(parent, entry)
        row:SetPoint("LEFT", parent, "LEFT", 0, 0)
        row:SetPoint("RIGHT", parent, "RIGHT", 0, 0)
        if i == 1 then
            row:SetPoint("TOP", prev, "BOTTOM", 0, -2)
            firstRow = row
        else
            row:SetPoint("TOP", prev, "BOTTOM", 0, 0)
        end
        prev = row
    end
    local lastRow = prev

    -- Solo test section (anchored to last row — no hard-coded offsets)
    local soloHeader = MakeSectionHeader(parent, "Solo Test (no raid required)")
    soloHeader:SetPoint("TOPLEFT", lastRow, "BOTTOMLEFT", PAD_X, -6)
    local soloDivider = MakeDivider(parent)
    soloDivider:SetPoint("LEFT", soloHeader, "RIGHT", 8, 0)
    soloDivider:SetPoint("RIGHT", parent, "RIGHT", -PAD_X, 0)

    local sayCB = MakeCheckbox(parent, "/say debug mode",
        function() return L:IsSayDebugOn() end,
        function(v) L:SetSayDebug(v) end)
    sayCB:SetPoint("TOPLEFT", soloHeader, "BOTTOMLEFT", -4, -6)
    table.insert(refreshers, sayCB.Refresh)

    local sayTestBtn = MakeButton(parent, "Run /say test", 110, function()
        L:SetSayDebug(true)
        sayCB:Refresh()
        L:SayTest()
    end)
    sayTestBtn:SetPoint("LEFT", sayCB, "RIGHT", 140, 0)

    local soloBody = MakeBodyText(parent,
        "With /say debug on, any /say message renders into the next slot — press\n"
        .. "Run to fire 5 real /say messages, or type anything yourself. Turn off\n"
        .. "before raiding so /say chatter can't drive the display.")
    soloBody:SetPoint("TOPLEFT", sayCB, "BOTTOMLEFT", 4, -4)
    soloBody:SetPoint("RIGHT", parent, "RIGHT", -PAD_X, 0)

    -- Fixed scroll-child height tall enough for all current content
    -- with a bit of headroom. If we add sections later, bump this.
    parent:SetHeight(560)
end

-- Refresh widget states from underlying module (called when tab shown)
function UI:Refresh()
    if not built then return end
    for _, fn in ipairs(refreshers) do
        pcall(fn)
    end
end
