local _, WN = ...

local function TrackerRow(parent, y, label, clickable)
    local row = CreateFrame(clickable and "Button" or "Frame", nil, parent, clickable and "BackdropTemplate" or nil)
    row:SetPoint("TOPLEFT", 10, y)
    row:SetPoint("TOPRIGHT", -10, y)
    row:SetHeight(24)
    row.check = row:CreateTexture(nil, "ARTWORK")
    row.check:SetSize(15,15)
    row.check:SetPoint("LEFT",0,0)
    row.check:SetTexture(WN.icons.check)
    row.check:SetVertexColor(unpack(WN.colors.green))
    row.box = row:CreateTexture(nil, "BACKGROUND")
    row.box:SetSize(15,15); row.box:SetPoint("LEFT",0,0); row.box:SetColorTexture(0.02,0.04,0.05,1)
    row.label = WN:CreateText(row, 9, WN.colors.text, "LEFT")
    row.label:SetPoint("LEFT",22,0); row.label:SetPoint("RIGHT",-45,0); row.label:SetText(label or "")
    row.value = WN:CreateText(row, 8, WN.colors.muted, "RIGHT")
    row.value:SetPoint("RIGHT",0,0); row.value:SetWidth(42)
    if clickable then
        row:SetScript("OnEnter", function(self) self.label:SetTextColor(unpack(WN.colors.accent)) end)
        row:SetScript("OnLeave", function(self) self.label:SetTextColor(unpack(WN.colors.text)) end)
    end
    return row
end

function WN:CreateTracker()
    if self.tracker then return end
    local tracker = CreateFrame("Frame", "WoWNextTrackerFrame", UIParent, "BackdropTemplate")
    tracker:SetSize(248, 700)
    tracker:SetPoint("TOPLEFT", self.frame, "TOPRIGHT", 14, 0)
    tracker:SetFrameStrata("HIGH")
    tracker:SetClampedToScreen(true)
    tracker:SetMovable(true)
    tracker:EnableMouse(true)
    self.ApplyBackdrop(tracker, self.colors.bg, self.colors.border)
    tracker.tint = tracker:CreateTexture(nil, "BACKGROUND")
    tracker.tint:SetAllPoints()
    tracker.tint:SetColorTexture(self.colors.accent[1], self.colors.accent[2], self.colors.accent[3], 0.018)
    tracker:Hide()
    self.tracker = tracker

    local top = CreateFrame("Frame", nil, tracker, "BackdropTemplate")
    top:SetPoint("TOPLEFT",0,0); top:SetPoint("TOPRIGHT",0,0); top:SetHeight(40)
    self.ApplyBackdrop(top, self.colors.bgDeep, self.colors.borderSoft)
    top.glow = top:CreateTexture(nil, "BACKGROUND")
    top.glow:SetAllPoints()
    top.glow:SetColorTexture(self.colors.accent[1], self.colors.accent[2], self.colors.accent[3], 0.12)
    top.accentLine = top:CreateTexture(nil, "ARTWORK")
    top.accentLine:SetPoint("BOTTOMLEFT",0,0)
    top.accentLine:SetPoint("BOTTOMRIGHT",0,0)
    top.accentLine:SetHeight(2)
    top.accentLine:SetColorTexture(self.colors.accent[1], self.colors.accent[2], self.colors.accent[3], 0.75)
    tracker.top = top
    top.title = self:CreateText(top, 12, self.colors.text, "LEFT"); top.title:SetPoint("LEFT",12,0); top.title:SetText(self:T("TRACKER"))
    top.close = self:CreateButton(top,24,24,"×",function() WN.db.settings.showTracker=false; WN:ApplySettings(); WN:UpdateSettingsSection() end); top.close:SetPoint("RIGHT",-8,0)
    top:RegisterForDrag("LeftButton")
    top:SetScript("OnDragStart", function()
        if WN.editorMode or not WN.db.settings.lockTracker then tracker:StartMoving() end
    end)
    top:SetScript("OnDragStop", function() tracker:StopMovingOrSizing(); WN:SaveTrackerPosition() end)

    tracker.daily = self:CreatePanel(tracker, self:T("DAILY_GOALS"), 228, 164); tracker.daily:SetPoint("TOPLEFT",10,-50)
    tracker.daily.rows = {}
    for i=1,5 do
        local row=TrackerRow(tracker.daily,-38-(i-1)*24,self:T("DAILY_"..i),true); row.index=i
        row:SetScript("OnClick", function(self) WN:ToggleDailyGoal(self.index) end)
        tracker.daily.rows[i]=row
    end

    tracker.weekly = self:CreatePanel(tracker, self:T("WEEKLY_GOALS"), 228, 164); tracker.weekly:SetPoint("TOPLEFT",10,-224)
    tracker.weekly.rows = {}
    local week={{"WEEKLY_MPLUS","MYTHIC_PLUS"},{"WEEKLY_RAID","RAID"},{"WEEKLY_WORLD","DELVES_WORLD"},{"WEEKLY_PVP","PVP"},{"WEEKLY_VAULT","VAULT"}}
    for i,def in ipairs(week) do local row=TrackerRow(tracker.weekly,-38-(i-1)*24,self:T(def[1]),false); row.dataKey=def[2]; row.textKey=def[1]; tracker.weekly.rows[i]=row end

    tracker.events = self:CreatePanel(tracker, self:T("ACTIVE_EVENTS"), 228, 118); tracker.events:SetPoint("TOPLEFT",10,-398)
    tracker.events.rows={}
    local events={{"SEASON_EVENT",self.icons.info},{"RAID_EVENT",self.icons.raid},{"MPLUS_EVENT",self.icons.mythic}}
    for i,def in ipairs(events) do local row=TrackerRow(tracker.events,-38-(i-1)*24,self:T(def[1]),false); row.check:SetTexture(def[2]); row.check:SetVertexColor(1,1,1,1); row.box:Hide(); row.textKey=def[1]; tracker.events.rows[i]=row end

    tracker.notifications = self:CreatePanel(tracker, self:T("NOTIFICATIONS"), 228, 128); tracker.notifications:SetPoint("TOPLEFT",10,-526)
    tracker.notifications.rows={}
    for i=1,3 do local row=TrackerRow(tracker.notifications,-38-(i-1)*26,"",false); row.check:SetTexture(self.icons.info); row.check:SetVertexColor(unpack(self.colors.accent)); row.box:Hide(); tracker.notifications.rows[i]=row end

    tracker.reset = self:CreateButton(tracker, 228, 32, self:T("RESET"), function() WN:ResetDailyGoals() end)
    tracker.reset:SetPoint("BOTTOMLEFT",10,8)
end

function WN:CheckGoalResets()
    if not self.db then return end
    local now = time()
    local reset = self:GetResetInfo()
    if not self.db.goalCycles.dailyNext or now >= self.db.goalCycles.dailyNext then
        self.db.dailyGoals = {}
        self.db.goalCycles.dailyNext = now + math.max(60, reset.daily or 86400)
    end
    if not self.db.goalCycles.weeklyNext or now >= self.db.goalCycles.weeklyNext then
        self.db.goalCycles.weeklyNext = now + math.max(60, reset.weekly or 604800)
    end
end

function WN:ToggleDailyGoal(index)
    self:CheckGoalResets()
    self.db.dailyGoals[index] = not self.db.dailyGoals[index]
    if self.cachedOverview then self:UpdateTracker(self.cachedOverview) else self:RefreshAll() end
end

function WN:ResetDailyGoals()
    self.db.dailyGoals = {}
    if self.cachedOverview then self:UpdateTracker(self.cachedOverview) end
end

function WN:SaveTrackerPosition()
    if not self.db or not self.tracker then return end
    if self.editorMode and self.SnapFramePosition then self:SnapFramePosition(self.tracker, 10) end
    local point, _, relativePoint, x, y = self.tracker:GetPoint(1)
    self.db.positions.tracker = { point=point, relativePoint=relativePoint, x=x, y=y }
end

function WN:RestoreTrackerPosition()
    if not self.db or not self.tracker then return end
    local pos=self.db.positions and self.db.positions.tracker
    if type(pos)=="table" and pos.point then self.tracker:ClearAllPoints(); self.tracker:SetPoint(pos.point,UIParent,pos.relativePoint or pos.point,pos.x or 0,pos.y or 0) end
end

function WN:UpdateTrackerStaticTexts()
    if not self.tracker then return end
    local t=self.tracker; t.top.title:SetText(self:T("TRACKER")); t.daily.title:SetText(self:T("DAILY_GOALS")); t.weekly.title:SetText(self:T("WEEKLY_GOALS")); t.events.title:SetText(self:T("ACTIVE_EVENTS")); t.notifications.title:SetText(self:T("NOTIFICATIONS")); t.reset.label:SetText(self:T("RESET"))
    for i,row in ipairs(t.daily.rows) do row.label:SetText(self:T("DAILY_"..i)) end
    for _,row in ipairs(t.weekly.rows) do row.label:SetText(self:T(row.textKey)) end
    for _,row in ipairs(t.events.rows) do row.label:SetText(self:T(row.textKey)) end
end

function WN:UpdateTracker(data)
    if not self.tracker or not data then return end
    self:CheckGoalResets()
    for i,row in ipairs(self.tracker.daily.rows) do
        local done=self.db.dailyGoals[i]==true; row.check:SetShown(done); row.box:SetShown(not done); row.value:SetText("")
    end

    for _,row in ipairs(self.tracker.weekly.rows) do
        if row.dataKey=="VAULT" then
            local done=data.weekly.vaultAvailable or data.weekly.completedThresholds>0
            row.check:SetShown(done); row.box:SetShown(not done); row.value:SetText(data.weekly.completedThresholds.."/"..data.weekly.totalThresholds)
        else
            local g=data.weekly.groups[row.dataKey]
            local done=g and g.threshold>0 and g.progress>=g.threshold
            row.check:SetShown(done==true); row.box:SetShown(done~=true); row.value:SetText(g and g.threshold>0 and (g.progress.."/"..g.threshold) or self:T("NA"))
        end
    end

    local reset=data.resets or self:GetResetInfo()
    self.tracker.events.rows[1].value:SetText(self:FormatDuration(reset.weekly))
    self.tracker.events.rows[2].value:SetText(self:T("RAID"))
    self.tracker.events.rows[3].value:SetText(self:FormatNumber(data.character.mythicRating))

    local notices=self:BuildNotifications(data)
    for i,row in ipairs(self.tracker.notifications.rows) do
        if notices[i] then row:Show(); row.label:SetText(notices[i].text or ""); row.value:SetText(""); row.check:SetVertexColor(unpack((notices[i].severity or 1)>=3 and self.colors.yellow or self.colors.accent)) else row:Hide() end
    end
end
