-- EbonholdHubPickLog/EbonholdHubPickLog.lua
-- Minimap button + small control panel for the PickLog.
-- Loaded after EbonholdHub (Dependencies in .toc).

local PL = EbonholdHub.PickLog
local ST = EbonholdHub.SiteTheme
local SW = EbonholdHub.SiteWidgets
local C  = ST.C

local FLAT        = "Interface\\Buttons\\WHITE8X8"
local PANEL_W     = 300
local PANEL_H     = 195
local HEADER_H    = 38
local PAD         = 16
local CONTENT_W   = PANEL_W - PAD * 2   -- 268 — max label width

-- ── DB helper ─────────────────────────────────────────────────────────────────
local function DB()
    EbonholdHubPickLog = EbonholdHubPickLog or {}
    return EbonholdHubPickLog
end

local function EntryCount()
    local db = DB()
    if type(db.entries) == "table" then return #db.entries end
    return 0
end

-- ── Minimap Button ─────────────────────────────────────────────────────────────
-- Standard size 24×24 so the border ring sits flush against the minimap edge.

-- Exact LibDBIcon-1.0 layout: 31×31 button, 53×53 overlay at TOPLEFT,
-- 20×20 background + icon at (7, -5), TexCoord trims icon corners.
local minimapBtn = CreateFrame("Button", "EBHPickLogMinimapBtn", Minimap)
minimapBtn:SetSize(31, 31)
minimapBtn:SetFrameStrata("MEDIUM")
minimapBtn:SetFrameLevel(8)
minimapBtn:SetHighlightTexture("Interface\\Minimap\\UI-Minimap-ZoomButton-Highlight")

local btnOverlay = minimapBtn:CreateTexture(nil, "OVERLAY")
btnOverlay:SetSize(53, 53)
btnOverlay:SetTexture("Interface\\Minimap\\MiniMap-TrackingBorder")
btnOverlay:SetPoint("TOPLEFT")

local btnBg = minimapBtn:CreateTexture(nil, "BACKGROUND")
btnBg:SetSize(20, 20)
btnBg:SetTexture("Interface\\Minimap\\UI-Minimap-Background")
btnBg:SetPoint("TOPLEFT", minimapBtn, "TOPLEFT", 7, -5)

local btnIcon = minimapBtn:CreateTexture(nil, "ARTWORK")
btnIcon:SetSize(20, 20)
btnIcon:SetTexture("Interface\\Icons\\INV_Misc_Note_06")
btnIcon:SetTexCoord(0.05, 0.95, 0.05, 0.95)
btnIcon:SetPoint("TOPLEFT", minimapBtn, "TOPLEFT", 7, -5)

-- Position uses degrees (stored) → radians, respects minimap shape
local function UpdateMinimapPos()
    local deg   = DB().minimapPos or 225
    local angle = math.rad(deg)
    local x, y  = math.cos(angle) * 80, math.sin(angle) * 80
    minimapBtn:ClearAllPoints()
    minimapBtn:SetPoint("CENTER", Minimap, "CENTER", x, y)
end

-- ── Panel ──────────────────────────────────────────────────────────────────────

local panel = CreateFrame("Frame", "EBHPickLogPanel", UIParent)
panel:SetSize(PANEL_W, PANEL_H)
panel:SetPoint("CENTER")
panel:SetFrameStrata("DIALOG")
panel:SetMovable(true)
panel:EnableMouse(true)
panel:RegisterForDrag("LeftButton")
panel:SetScript("OnDragStart", panel.StartMoving)
panel:SetScript("OnDragStop",  panel.StopMovingOrSizing)
panel:Hide()

SW.Fill(panel, C.bg)
SW.ThinBorder(panel, C.border, 1)

-- ── Header ─────────────────────────────────────────────────────────────────────
local header = CreateFrame("Frame", nil, panel)
header:SetHeight(HEADER_H)
header:SetPoint("TOPLEFT",  panel, "TOPLEFT")
header:SetPoint("TOPRIGHT", panel, "TOPRIGHT")
SW.Fill(header, C.bgHeader)

-- 2px accent stripe at the very top
local stripe = header:CreateTexture(nil, "OVERLAY")
stripe:SetTexture(FLAT)
stripe:SetHeight(2)
stripe:SetPoint("TOPLEFT",  header, "TOPLEFT")
stripe:SetPoint("TOPRIGHT", header, "TOPRIGHT")
stripe:SetVertexColor(C.accent[1], C.accent[2], C.accent[3], 1)

-- header icon
local hIcon = header:CreateTexture(nil, "OVERLAY")
hIcon:SetTexture("Interface\\Icons\\INV_Misc_Note_06")
hIcon:SetSize(18, 18)
hIcon:SetPoint("LEFT", header, "LEFT", 14, 0)

-- header title
local titleLabel = SW.Label(header, "PICKLOG", 11, C.accent, false, "semibold")
titleLabel:SetPoint("LEFT", hIcon, "RIGHT", 7, 0)

-- close button — use WoW's built-in UIPanelCloseButton so the X renders properly
local closeBtn = CreateFrame("Button", nil, header, "UIPanelCloseButton")
closeBtn:SetSize(22, 22)
closeBtn:SetPoint("RIGHT", header, "RIGHT", -4, 0)
closeBtn:SetScript("OnClick", function() panel:Hide() end)

-- separator under header
local sep1 = panel:CreateTexture(nil, "ARTWORK")
sep1:SetTexture(FLAT)
sep1:SetHeight(1)
sep1:SetPoint("TOPLEFT",  panel, "TOPLEFT",  0, -HEADER_H)
sep1:SetPoint("TOPRIGHT", panel, "TOPRIGHT", 0, -HEADER_H)
sep1:SetVertexColor(C.border[1], C.border[2], C.border[3], 1)

-- ── Stats block ────────────────────────────────────────────────────────────────

local statsLabel = SW.Label(panel, "", 12, C.text, false, "regular")
statsLabel:SetPoint("TOPLEFT", panel, "TOPLEFT", PAD, -55)
statsLabel:SetWidth(CONTENT_W)

local infoLabel = SW.Label(panel, "", 11, C.textDim, false, "regular")
infoLabel:SetPoint("TOPLEFT", statsLabel, "BOTTOMLEFT", 0, -5)
infoLabel:SetWidth(CONTENT_W)
infoLabel:SetWordWrap(false)    -- single line; long names get clipped, not wrapped

local function RefreshStats()
    local count = EntryCount()
    statsLabel:SetText(string.format(
        "|cff%02x%02x%02xPickLog|r  ·  |cffffcc00%d|r offers recorded",
        math.floor(C.accent[1] * 255),
        math.floor(C.accent[2] * 255),
        math.floor(C.accent[3] * 255),
        count
    ))

    local char  = (UnitName and UnitName("player")) or "?"
    local realm = (GetRealmName and GetRealmName()) or ""
    local build = EbonholdHub.Build
        and EbonholdHub.Build.GetActive
        and EbonholdHub.Build.GetActive()
    local buildName = (build and build.title) or "no build"
    local charStr = realm ~= "" and (char .. " — " .. realm) or char
    infoLabel:SetText(charStr .. "  |cff555566·|r  " .. buildName)
end

-- ── Divider before buttons ─────────────────────────────────────────────────────

local sep2 = panel:CreateTexture(nil, "ARTWORK")
sep2:SetTexture(FLAT)
sep2:SetHeight(1)
sep2:SetPoint("TOPLEFT",  panel, "TOPLEFT",  PAD,  -108)
sep2:SetPoint("TOPRIGHT", panel, "TOPRIGHT", -PAD, -108)
sep2:SetVertexColor(C.border[1], C.border[2], C.border[3], 0.6)

-- ── Action Buttons ─────────────────────────────────────────────────────────────
-- 3 equal-width buttons with 8px gaps inside the content width

local BTN_GAP = 8
local BTN_W   = math.floor((CONTENT_W - BTN_GAP * 2) / 3)

local function MakeButton(text, col, onClick)
    local x = PAD + (col - 1) * (BTN_W + BTN_GAP)
    local btn = SW.CreateOutlineButton(panel, text, BTN_W)
    btn:SetPoint("TOPLEFT", panel, "TOPLEFT", x, -122)
    btn:SetScript("OnClick", onClick)
    return btn
end

-- Save Log → export then /reload so the file is actually written to disk
MakeButton("Save Log", 1, function()
    PL.Export()
    ReloadUI()
end)

-- Clear → confirm popup → clear then /reload
MakeButton("Clear", 2, function()
    if not StaticPopupDialogs["EBH_PICKLOG_CLEAR"] then
        StaticPopupDialogs["EBH_PICKLOG_CLEAR"] = {
            text         = "Clear the PickLog? This cannot be undone.",
            button1      = "Clear",
            button2      = "Cancel",
            OnAccept     = function()
                PL.Clear()
                ReloadUI()
            end,
            timeout      = 0,
            whileDead    = true,
            hideOnEscape = true,
        }
    end
    StaticPopup_Show("EBH_PICKLOG_CLEAR")
end)

-- Last 5 → just print to chat, no reload needed
MakeButton("Last 5", 3, function()
    PL.PrintLast(5)
end)

-- ── Footer note ────────────────────────────────────────────────────────────────

local footerNote = SW.Label(
    panel,
    "WTF/Account/.../SavedVariables/EbonholdHubPickLog.lua",
    9, C.textMuted, false, "regular"
)
footerNote:SetPoint("BOTTOM", panel, "BOTTOM", 0, 10)

-- ── Minimap Button click / tooltip ────────────────────────────────────────────

minimapBtn:SetScript("OnEnter", function(self)
    if self.isMoving then return end
    GameTooltip:SetOwner(self, "ANCHOR_LEFT")
    GameTooltip:SetText("EbonholdHub PickLog", 1, 1, 1)
    GameTooltip:AddLine(EntryCount() .. " offers recorded", 0.8, 0.8, 0.8)
    GameTooltip:AddLine(" ")
    GameTooltip:AddLine("Left-click: open panel",   C.accent[1], C.accent[2], C.accent[3])
    GameTooltip:AddLine("Right-click: save + reload", 0.7, 0.7, 0.7)
    GameTooltip:AddLine("Drag: reposition",           0.7, 0.7, 0.7)
    GameTooltip:Show()
end)
minimapBtn:SetScript("OnLeave", function() GameTooltip:Hide() end)

minimapBtn:RegisterForClicks("LeftButtonUp", "RightButtonUp")
minimapBtn:SetScript("OnClick", function(self, button)
    if button == "RightButton" then
        PL.Export()
        ReloadUI()
        return
    end
    if panel:IsShown() then
        panel:Hide()
    else
        RefreshStats()
        panel:Show()
    end
end)

-- ── Drag to reposition ─────────────────────────────────────────────────────────

minimapBtn:RegisterForDrag("LeftButton")
minimapBtn:SetMovable(false)

minimapBtn:SetScript("OnMouseDown", function()
    btnIcon:SetTexCoord(0, 1, 0, 1)
end)
minimapBtn:SetScript("OnMouseUp", function()
    btnIcon:SetTexCoord(0.05, 0.95, 0.05, 0.95)
end)

minimapBtn:SetScript("OnDragStart", function(self)
    self:LockHighlight()
    btnIcon:SetTexCoord(0, 1, 0, 1)
    self.isMoving = true
    GameTooltip:Hide()
    self:SetScript("OnUpdate", function()
        local mx, my = Minimap:GetCenter()
        local px, py = GetCursorPosition()
        local scale  = Minimap:GetEffectiveScale()
        DB().minimapPos = math.deg(math.atan2(py / scale - my, px / scale - mx)) % 360
        UpdateMinimapPos()
    end)
end)
minimapBtn:SetScript("OnDragStop", function(self)
    self:SetScript("OnUpdate", nil)
    btnIcon:SetTexCoord(0.05, 0.95, 0.05, 0.95)
    self:UnlockHighlight()
    self.isMoving = nil
end)

-- ── Init ───────────────────────────────────────────────────────────────────────

local initFrame = CreateFrame("Frame")
initFrame:RegisterEvent("PLAYER_LOGIN")
initFrame:SetScript("OnEvent", function()
    UpdateMinimapPos()
end)
