local _, ESKP = ...

ESKP.UI = { filter = "ALL", selectedID = nil }

local colors = {
    accent = { 0.38, 0.84, 1.00 },
    accentSoft = { 0.16, 0.40, 0.56 },
    background = { 0.025, 0.035, 0.055, 0.97 },
    panel = { 0.065, 0.085, 0.125, 0.96 },
    panelRaised = { 0.09, 0.12, 0.18, 0.98 },
    muted = { 0.59, 0.66, 0.76 },
    green = { 0.25, 0.90, 0.56 },
}

local function text(parent, size, color)
    local font = parent:CreateFontString(nil, "OVERLAY", "GameFontNormal")
    font:SetFont(STANDARD_TEXT_FONT, size, "")
    font:SetTextColor(unpack(color or { 1, 1, 1 }))
    font:SetJustifyH("LEFT")
    font:SetJustifyV("TOP")
    return font
end

local function button(parent, label, width)
    local b = CreateFrame("Button", nil, parent, "BackdropTemplate")
    b:SetSize(width, 27)
    b:SetBackdrop({ bgFile = "Interface\\Buttons\\WHITE8X8", edgeFile = "Interface\\Buttons\\WHITE8X8", edgeSize = 1 })
    b:SetBackdropColor(0.075, 0.10, 0.15, 1)
    b:SetBackdropBorderColor(0.19, 0.28, 0.38, 1)
    b.label = text(b, 11, { 0.80, 0.86, 0.94 })
    b.label:SetPoint("CENTER", 0, 0)
    b.label:SetText(label)
    b:SetScript("OnEnter", function(frame)
        if not frame.active then frame:SetBackdropColor(0.11, 0.17, 0.24, 1) end
    end)
    b:SetScript("OnLeave", function(frame)
        if not frame.active then frame:SetBackdropColor(0.075, 0.10, 0.15, 1) end
    end)
    function b:SetActive(active)
        self.active = active
        if active then
            self:SetBackdropColor(0.08, 0.27, 0.39, 1)
            self:SetBackdropBorderColor(unpack(colors.accent))
            self.label:SetTextColor(unpack(colors.accent))
        else
            self:SetBackdropColor(0.075, 0.10, 0.15, 1)
            self:SetBackdropBorderColor(0.19, 0.28, 0.38, 1)
            self.label:SetTextColor(0.80, 0.86, 0.94)
        end
    end
    return b
end

function ESKP.UI:Initialize()
    if self.frame then return end
    local f = CreateFrame("Frame", "ESKPursuitFrame", UIParent, "BackdropTemplate")
    f:SetSize(940, 590)
    f:SetPoint("CENTER")
    f:SetFrameStrata("DIALOG")
    f:SetClampedToScreen(true)
    f:SetMovable(true)
    f:EnableMouse(true)
    f:RegisterForDrag("LeftButton")
    f:SetScript("OnDragStart", f.StartMoving)
    f:SetScript("OnDragStop", function(frame)
        frame:StopMovingOrSizing()
        local point, _, relativePoint, x, y = frame:GetPoint(1)
        ESKP.db.settings.window = { point = point, relativePoint = relativePoint, x = x, y = y }
    end)
    f:SetBackdrop({ bgFile = "Interface\\Buttons\\WHITE8X8", edgeFile = "Interface\\Buttons\\WHITE8X8", edgeSize = 1 })
    f:SetBackdropColor(unpack(colors.background))
    f:SetBackdropBorderColor(0.22, 0.43, 0.58, 1)
    f:Hide()
    self.frame = f

    local title = text(f, 22, colors.accent)
    title:SetPoint("TOPLEFT", 22, -18)
    title:SetText("ESK  /  PURSUIT")
    local subtitle = text(f, 12, colors.muted)
    subtitle:SetPoint("TOPLEFT", title, "BOTTOMLEFT", 0, -3)
    subtitle:SetText("High-value farms, exact paths, and your attempt history")

    local close = button(f, "X", 28)
    close:SetPoint("TOPRIGHT", -18, -18)
    close:SetScript("OnClick", function() f:Hide() end)

    local filterLabels = { { "ALL", "Featured" }, { "READY", "Ready now" }, { "WATCHLIST", "Watchlist" }, { "MOUNT", "Mounts" }, { "PET", "Pets" }, { "TRANSMOG", "Transmog" } }
    self.filterButtons = {}
    local previous
    for _, entry in ipairs(filterLabels) do
        local key, label = entry[1], entry[2]
        local b = button(f, label, key == "TRANSMOG" and 82 or 72)
        if previous then b:SetPoint("LEFT", previous, "RIGHT", 6, 0) else b:SetPoint("TOPLEFT", 22, -70) end
        b:SetScript("OnClick", function() self.filter = key; self:Refresh() end)
        self.filterButtons[key] = b
        previous = b
    end

    local left = CreateFrame("Frame", nil, f, "BackdropTemplate")
    left:SetPoint("TOPLEFT", 18, -105)
    left:SetPoint("BOTTOMLEFT", 18, 18)
    left:SetWidth(300)
    left:SetBackdrop({ bgFile = "Interface\\Buttons\\WHITE8X8" })
    left:SetBackdropColor(unpack(colors.panel))
    self.list = left
    local scroll = CreateFrame("ScrollFrame", nil, left, "UIPanelScrollFrameTemplate")
    scroll:SetPoint("TOPLEFT", 5, -5)
    scroll:SetPoint("BOTTOMRIGHT", -27, 5)
    local listContent = CreateFrame("Frame", nil, scroll)
    listContent:SetSize(268, 1)
    scroll:SetScrollChild(listContent)
    self.listScroll = scroll
    self.listContent = listContent

    local right = CreateFrame("Frame", nil, f, "BackdropTemplate")
    right:SetPoint("TOPLEFT", left, "TOPRIGHT", 12, 0)
    right:SetPoint("BOTTOMRIGHT", -18, 18)
    right:SetBackdrop({ bgFile = "Interface\\Buttons\\WHITE8X8" })
    right:SetBackdropColor(unpack(colors.panel))
    self.detail = right
    self:InitializeTrackerPanel()
end

function ESKP.UI:InitializeTrackerPanel()
    local f = CreateFrame("Frame", "ESKPursuitTrackerFrame", UIParent, "BackdropTemplate")
    f:SetSize(270, 94)
    f:SetPoint("RIGHT", -35, 0)
    f:SetFrameStrata("DIALOG")
    f:SetClampedToScreen(true)
    f:SetMovable(true)
    f:EnableMouse(true)
    f:RegisterForDrag("LeftButton")
    f:SetScript("OnDragStart", f.StartMoving)
    f:SetScript("OnDragStop", function(frame)
        frame:StopMovingOrSizing()
        local point, _, relativePoint, x, y = frame:GetPoint(1)
        ESKP.db.settings.trackerWindow = { point = point, relativePoint = relativePoint, x = x, y = y, hidden = false }
    end)
    f:SetBackdrop({ bgFile = "Interface\\Buttons\\WHITE8X8", edgeFile = "Interface\\Buttons\\WHITE8X8", edgeSize = 1 })
    f:SetBackdropColor(unpack(colors.background))
    f:SetBackdropBorderColor(0.22, 0.43, 0.58, 1)
    f:Hide()
    self.tracker = f

    local title = text(f, 14, colors.accent)
    title:SetPoint("TOPLEFT", 13, -11)
    title:SetText("TRACKED PURSUITS")
    local open = button(f, "Open", 50)
    open:SetPoint("TOPRIGHT", -10, -7)
    open:SetScript("OnClick", function() self:Show("WATCHLIST") end)
    self.trackerRows = {}
end

function ESKP.UI:RefreshList()
    if self.rows then for _, row in ipairs(self.rows) do row:Hide() end end
    self.rows = self.rows or {}
    local targets = ESKP:GetTargets(self.filter)
    if #targets > 0 and (not self.selectedID or not ESKP:GetTarget(self.selectedID)) then self.selectedID = targets[1].id end
    local selectedPresent = false
    for _, target in ipairs(targets) do if target.id == self.selectedID then selectedPresent = true end end
    if not selectedPresent then self.selectedID = targets[1] and targets[1].id or nil end
    for index, target in ipairs(targets) do
        local row = self.rows[index]
        if not row then
            row = CreateFrame("Button", nil, self.listContent, "BackdropTemplate")
            row:SetSize(268, 43)
            row:SetBackdrop({ bgFile = "Interface\\Buttons\\WHITE8X8" })
            row.name = text(row, 13, { 1, 1, 1 })
            row.name:SetPoint("TOPLEFT", 10, -7)
            row.name:SetWidth(246)
            row.name:SetWordWrap(false)
            row.meta = text(row, 10, colors.muted)
            row.meta:SetPoint("TOPLEFT", row.name, "BOTTOMLEFT", 0, -1)
            row:SetScript("OnClick", function(frame) self.selectedID = frame.targetID; self:Refresh() end)
            self.rows[index] = row
        end
        row.targetID = target.id
        row:SetPoint("TOPLEFT", 0, -5 - (index - 1) * 47)
        row.name:SetText((ESKP:IsWatched(target.id) and "|TInterface\\Buttons\\UI-CheckBox-Check:14:14:0:0:64:64:0:64:0:64|t " or "") .. target.name)
        row.meta:SetText(target.type .. "  •  " .. target.reset)
        if target.id == self.selectedID then
            row:SetBackdropColor(0.10, 0.22, 0.31, 1)
        else
            row:SetBackdropColor(0.055, 0.07, 0.11, 1)
        end
        row:Show()
    end
    self.listContent:SetHeight(math.max(self.list:GetHeight() - 10, #targets * 47 + 8))
    if #targets == 0 then
        self.empty = self.empty or text(self.list, 13, colors.muted)
        self.empty:SetPoint("TOPLEFT", 14, -15)
        self.empty:SetText("No pursuits here yet.")
        self.empty:Show()
    elseif self.empty then self.empty:Hide() end
end

function ESKP.UI:RefreshDetail()
    if self.detailContent then self.detailContent:Hide() end
    local target = self.selectedID and ESKP:GetTarget(self.selectedID)
    if not target then return end
    local state = ESKP:GetTargetState(target.id)
    local content = CreateFrame("Frame", nil, self.detail)
    content:SetAllPoints()
    self.detailContent = content

    local title = text(content, 20, colors.accent)
    title:SetPoint("TOPLEFT", 18, -16)
    title:SetText(target.name)
    local tags = text(content, 12, colors.green)
    tags:SetPoint("TOPLEFT", title, "BOTTOMLEFT", 0, -4)
    tags:SetText(target.type .. "  •  " .. target.value .. (target.marketable and "  •  MARKETABLE" or ""))

    local watch = button(content, ESKP:IsWatched(target.id) and "Unwatch" or "Track pursuit", 110)
    watch:SetPoint("TOPRIGHT", -18, -18)
    watch:SetScript("OnClick", function()
        ESKP:ToggleWatch(target.id)
        self:Refresh()
    end)
    local attempt = button(content, "Log attempt", 100)
    attempt:SetPoint("TOPRIGHT", watch, "BOTTOMRIGHT", 0, -7)
    attempt:SetScript("OnClick", function()
        ESKP:LogAttempt(target.id)
        ESKP:Print("Attempt logged for " .. target.name .. ".")
        self:Refresh()
    end)

    local info = text(content, 13, { 0.88, 0.9, 0.95 })
    info:SetPoint("TOPLEFT", 18, -77)
    info:SetWidth(540)
    info:SetSpacing(4)
    info:SetText("|cff9fadc2SOURCE|r  " .. target.source .. "\n|cff9fadc2ZONE|r  " .. target.zone .. "\n|cff9fadc2ATTEMPT WINDOW|r  " .. target.reset .. "\n|cff9fadc2DROP TYPE|r  " .. target.chance)

    local guideTitle = text(content, 14, colors.accent)
    guideTitle:SetPoint("TOPLEFT", 18, -164)
    guideTitle:SetText("YOUR EXACT PATH")
    local guide = text(content, 13, { 0.9, 0.92, 0.96 })
    guide:SetPoint("TOPLEFT", guideTitle, "BOTTOMLEFT", 0, -7)
    guide:SetWidth(540)
    guide:SetSpacing(5)
    local steps = {}
    for index, step in ipairs(target.steps) do steps[#steps + 1] = index .. ". " .. step end
    guide:SetText(table.concat(steps, "\n"))

    local history = text(content, 12, colors.muted)
    history:SetPoint("BOTTOMLEFT", 18, 74)
    local last = state.lastAttemptAt and date("%d %b %Y", state.lastAttemptAt) or "Never"
    history:SetText("ATTEMPT HISTORY  " .. (state.attempts or 0) .. " attempts  •  Last attempt: " .. last)

    local notesLabel = text(content, 12, colors.muted)
    notesLabel:SetPoint("BOTTOMLEFT", 18, 49)
    notesLabel:SetText("PERSONAL NOTES")
    local notes = CreateFrame("EditBox", nil, content, "InputBoxTemplate")
    notes:SetPoint("BOTTOMLEFT", 18, 20)
    notes:SetSize(405, 24)
    notes:SetAutoFocus(false)
    notes:SetText(state.notes or "")
    notes:SetScript("OnEnterPressed", function(box)
        ESKP:SaveNotes(target.id, box:GetText())
        box:ClearFocus()
        ESKP:Print("Notes saved.")
    end)
    local save = button(content, "Save", 60)
    save:SetPoint("LEFT", notes, "RIGHT", 8, 0)
    save:SetScript("OnClick", function() ESKP:SaveNotes(target.id, notes:GetText()); ESKP:Print("Notes saved.") end)
end

function ESKP.UI:Refresh()
    for key, b in pairs(self.filterButtons) do b:SetActive(key == self.filter) end
    self:RefreshList()
    self:RefreshDetail()
    self:RefreshTracker()
end

function ESKP.UI:RefreshTracker()
    local watched = ESKP:GetTargets("WATCHLIST")
    if #watched == 0 then
        self.tracker:Hide()
        return
    end
    for _, row in ipairs(self.trackerRows) do row:Hide() end
    local visible = math.min(#watched, 6)
    self.tracker:SetHeight(43 + visible * 26)
    for index = 1, visible do
        local target = watched[index]
        local row = self.trackerRows[index]
        if not row then
            row = CreateFrame("Button", nil, self.tracker, "BackdropTemplate")
            row:SetSize(244, 23)
            row:SetBackdrop({ bgFile = "Interface\\Buttons\\WHITE8X8" })
            row.label = text(row, 11, { 0.92, 0.94, 0.98 })
            row.label:SetPoint("LEFT", 6, 0)
            row.label:SetPoint("RIGHT", -5, 0)
            row.label:SetJustifyV("MIDDLE")
            row:SetScript("OnClick", function(frame)
                self.selectedID = frame.targetID
                self:Show("WATCHLIST")
            end)
            self.trackerRows[index] = row
        end
        local state = ESKP:GetTargetState(target.id)
        row.targetID = target.id
        row:SetPoint("TOPLEFT", 13, -36 - (index - 1) * 26)
        row:SetBackdropColor(0.055, 0.08, 0.12, 1)
        row.label:SetText("|TInterface\\Buttons\\UI-CheckBox-Check:14:14:0:0:64:64:0:64:0:64|t " .. target.name .. "  |cff9fadc2" .. (state.attempts or 0) .. " attempts|r")
        row:Show()
    end
    if not ESKP.db.settings.trackerWindow.hidden then self.tracker:Show() end
end

function ESKP.UI:Show(filter)
    if filter then self.filter = filter end
    self.frame:Show()
    self:Refresh()
end

function ESKP.UI:Hide() self.frame:Hide() end
function ESKP.UI:Toggle() if self.frame:IsShown() then self:Hide() else self:Show() end end
function ESKP.UI:ToggleTracker()
    local watched = ESKP:GetTargets("WATCHLIST")
    if #watched == 0 then
        ESKP:Print("Track a pursuit first to show the tracker.")
        return
    end
    local hidden = self.tracker:IsShown()
    self.tracker:Hide()
    ESKP.db.settings.trackerWindow.hidden = hidden
    if not hidden then self:RefreshTracker() end
end

function ESKP:InitializeUI()
    self.UI:Initialize()
    local saved = self.db.settings.window
    if saved.point then
        self.UI.frame:ClearAllPoints()
        self.UI.frame:SetPoint(saved.point, UIParent, saved.relativePoint, saved.x, saved.y)
    end
    local trackerSaved = self.db.settings.trackerWindow
    if trackerSaved.point then
        self.UI.tracker:ClearAllPoints()
        self.UI.tracker:SetPoint(trackerSaved.point, UIParent, trackerSaved.relativePoint, trackerSaved.x, trackerSaved.y)
    end
    self.UI:RefreshTracker()
end
