local _, ns = ...
local L = ns.L or {}

local DEFAULT_NEWS_ENTRIES = {
    {
        version = "0.9.97",
        date = "June 25, 2026",
        items = {
            "FIXED: WoW-Update-Versionsfix für Patch 12.0.7.",
        },
    },
    {
        version = "0.9.96",
        date = "May 27, 2026",
        items = {
            "ADDED: Neue Optionen für das XP-Popup vom Chronik-Tab: Es hat jetzt verschiedene Styles und die Größe kann geändert werden.",
            "FIXED: Das Feature Sammelknoten hat nicht funktioniert wie es sollte und konnte bei Filtern die alte Datenbank überschreiben. Es sollte nun dauerhaft korrekt speichern.",
            "UPDATED: Das Vaultloom-Fenster kann jetzt außerhalb des Bildschirmrands verschoben und mit /vl reset an die Standardposition zurückgebracht werden.",
        },
    },
    {
        version = "0.9.95",
        date = "May 24, 2026",
        items = {
            "ADDED: Neues Feature Ruhige Beute, kleines Gimmick um ein vereinfachtes Lootfenster von Beute und Truhen darzustellen.",
            "FIXED: ACCESS_VIOLATION error beim Ausloggen aufgrund vom Scannen von Dunkelmondjahrmarkt Quests.",
        },
    },
    {
        version = "0.9.94",
        date = "May 16, 2026",
        items = {
            "ADDED: Added the Delves weekly warband drop quest.",
            "FIXED: Gathering Nodes CPU usage reduced by removing unneeded stored side information. The feature now saves less data and runs much more stable.",
            "UPDATED: Compendium (Beta) received many Midnight fixes, added entries, promotion mount grouping, and item icon fallbacks.",
        },
    },
    {
        version = "0.9.932",
        date = "May 12, 2026",
        items = {
            "FIXED: Alts no longer receive Chronicle XP spam from Bountiful Delves; this activity now only counts correctly at level 90.",
            "FIXED: Lua error when using gathering professions inside instances while the Gathering Nodes feature was enabled.",
        },
    },
    {
        version = "0.9.93",
        date = "11. Mai 2026",
        items = {
            "UPDATED: Compendium decorations now read owned counts from the Housing catalog.",
            "UPDATED: Decoration progress now counts owned decorations as completed when at least one copy is owned.",
            "FIXED: Blizzard UI windows now open above the main Vaultloom window while Vaultloom still stays above normal action bars and regular UI.",
            "FIXED: The Vaultloom merchant window now supports Blizzard modified item clicks again, including item preview/dress-up and chat linking.",
            "FIXED: One-Click Processing no longer triggers a protected `Hide()` action blocked warning during combat; secure button cleanup is now delayed until combat ends.",
            "FIXED: Gathering node pins are now hidden while inside instances/dungeons, preventing outdoor gathering nodes from appearing on dungeon maps.",
            "FIXED: Gathering node snapshots are no longer saved while inside instances, preventing dungeon loot from being stored on outdoor maps.",
        },
    },
    {
        version = "0.9.92",
        date = "8. Mai 2026",
        items = {
            "NEW: Neuer Kompendium (Beta)-Tab. Zeigt sammelbare Midnight-Inhalte wie Reittiere, Haustiere, Spielzeuge, Dekorationen und Rezepte in einer durchsuchbaren Übersicht mit Filtern, Tooltips und Wegpunkten.",
            "NEW Feature Weltkarte: Sammelknoten. Vaultloom baut beim Sammeln eine eigene Datenbank für Bergbau, Kräuterkunde, Kürschnerei, Kochmaterialien, Holz und Fisch auf und zeigt gefundene Knoten auf Weltkarte und Minimap an.",
            "NEW Feature Weltkarte: Midnight-Schätze. Zeigt nicht eingesammelte Midnight-Schätze als Kartenpins an.",
            "NEW Feature Weltkarte: Berufswissen. Zeigt passende Berufswissens-Punkte für die aktiven Berufe des Charakters auf der Karte an.",
            "NEW: Neuer Vaultloom-Kartenbutton direkt auf der Weltkarte, um Kartenfeatures schnell ein- und auszuschalten.",
            "UPDATED: Kartenpins, Sammelknoten-Icons, Schatz-Icons und Rare-Pins optisch überarbeitet und besser lesbar gemacht.",
            "UPDATED: Blizzard-Fenster bewegen unterstützt mehr Standardfenster und vermeidet problematische Skalierung bei empfindlichen Blizzard-Ansichten.",
            "FIXED: Die Goldanzeige der Charaktere speichert jetzt zuverlässiger, damit Twinks nach dem Umloggen nicht mehr mit 0 Gold angezeigt werden.",
        },
    },
    {
        version = "0.9.91",
        date = "7. Mai 2026",
        items = {
            "FIXED: Die optionale automatische Questabgabe ist jetzt sicherer und gibt riskante NPC-Quests mit Belohnungsauswahl, Kosten oder mehreren möglichen Abgaben nicht mehr automatisch ab.",
            "FIXED: Gunst des Hofes gibt Chronik-XP jetzt nur noch einmal pro Woche für die Warband, wie die Housing-Weekly.",
        },
    },
    {
        version = "0.9.9",
        date = "7. Mai 2026",
        items = {
            "NEW: Zeigt die Berufs-Badges im Main-Tab jetzt für alle Charaktere an.",
            "NEW: Zeigt das Gold von jedem Charakter im Main-Tab an.",
            "NEW Feature Midnight Rare Mobs Kartensymbole: Auf der Map werden kleine Badges angezeigt, damit du siehst, wo die Rares spawnen.",
            "NEW Feature Händlerfilter: 3 verschiedene Modi, um Items beim Händler zu filtern: komplett neues Vaultloom-Händlerfenster, Filter-only mit originaler WoW-UI oder Mixed-Version mit beidem. Es ist quasi fast alles filterbar: Rezepte, Berufe, Ausrüstung, Dekor-Items und bereits erhaltene/bekannte Items. Zusätzlich wurde ein Blizzard-UI-Bug gefixt, der bei manchen Händlern die falsche Währung anzeigt.",
            "NEW Feature Quests automatisch annehmen und optional automatisch abgeben.",
            "NEW Feature Item-ID im Tooltip anzeigen lassen.",
            "FIXED: Hoffentlich zum allerletzten Mal das Prey-Fortschrittsbalken-System. In Silbermond sollte jetzt nicht mehr das Blizzard-UI aufploppen.",
            "ADDED: Support für mehr Sprachen: Italienisch, Portugiesisch und Russisch.",
        },
    },
    {
        version = "0.9.98",
        date = "6. Mai 2026",
        items = {
            "ADDED: Neue Weekly-Quests fuer Vereint gegen die Leere und Erzmagier Aethas im Pool.",
            "NEW: Voller Support fuer Kalender-Event-Quests: Dunkelmond-Jahrmarkt-Dailys, Weeklys und Abgaben werden jetzt getrackt.",
            "NEW: Dunkelmond-Jahrmarkt-Berufsquests wurden im Berufe-Tab hinzugefuegt.",
            "NEW: Neuer Bereich im PvE-Tab fuer Kalender-Events und zukuenftige spezielle WoW-Events.",
            "FIXED: Warband-Zeilenfilter speichert jetzt die letzte Einstellung beim Ausloggen.",
            "UPDATED: Chronik-XP: Globale Quests geben nur noch einmalig XP fuer den Charakter, der die Mission erfuellt.",
            "ANMERKUNG: Bitte meldet Bugs, Fehler oder Wuensche in der Curse-Comment-Section. Danke!",
        },
    },
    {
        version = "0.9.97",
        date = "4. Mai 2026",
        items = {
            "NEU Feature Blizzard Fenster Bewegen. Du kannst mit dem aktivierten Feature die meisten Standard-Blizzard-UI-Elemente mit Tastenkombos bewegen oder vergrößern/verkleinern.",
            "NEU Feature Einkaufsliste. Mit Button am Handwerks- und Auktionsfenster oder als eigener runder Mini-Button, den man verschieben und in der Größe einstellen kann.",
            "NEU Feature Vaultloom Bestand. Zählt alle Items in Taschen, Bank und Warband-Bank. Einmal auf Twinks einloggen und Bank, Warband-Bank und Taschen einmal öffnen, damit alles gezählt wird.",
            "UPDATE Vaultloom Armory visuelle Verbesserungen.",
            "UPDATE Vaultloom UI visuelle Verbesserungen.",
            "Geändert MAIN Charakter setzen Button entfernt. Funktioniert jetzt per Rechtsklick auf eine Charakterzeile.",
        },
    },
    {
        version = "0.9.963",
        date = "May 3, 2026",
        items = {
            "NEW: Chronicle tab XP popups can now be moved with a test popup and saved at your preferred position.",
            "UPDATED: Chronicle settings now have their own grouped options menu for display, badges, and popup controls.",
        },
    },
    {
        version = "0.9.96",
        date = "May 1, 2026",
        items = {
            "NEW: Vaultloom Armory is available as a new optional entry in the Features menu. Enable it there to add an extended character overview with gear checks, sockets, enchants, and compact combat stats.",
            "FIXED: Fixed the Rare Mobs Lua error caused by protected Blizzard tooltip names.",
            "UPDATED: Reworked the Features menu with category buttons, a scrollable feature list, checkboxes, and compact settings.",
        },
    },
    {
        version = "0.9.95",
        date = "April 30, 2026",
        items = {
            "NEW: The PvE tab now has a Rare Mobs menu for Midnight rares, daily kill status, mount status, and clickable Blizzard waypoints.",
        },
    },
    {
        version = "0.9.94",
        date = "April 29, 2026",
        items = {
            "FIXED: Great Vault max-reward progress for World / Delves / Prey now counts max-level activities correctly.",
            "FIXED: Chronicle XP popups now trigger more reliably for relevant Vaultloom tasks without needing to open the addon first.",
        },
    },
    {
        version = "0.9.93",
        date = "April 29, 2026",
        items = {
            "UPDATED: Added a new Void Assaults quest to the PvE event pool.",
        },
    },
    {
        version = "0.9.92",
        date = "April 29, 2026",
        items = {
            "NEW: Chronicle quest XP popup notifications can now be disabled separately in Options while keeping the rest of Chronicle enabled.",
            "NEW: Mythic+ now has a Warband Keys button below the current keystone panel, showing all alts and saved keystones at a glance. Log in once on each alt so Vaultloom can save its key.",
            "NEW: Added the Decor Duel daily quest row to the PvE Daily tab.",
            "UPDATED: Added the new Archmage Aethas weekly quest and expanded the PvP weekly quest pool.",
            "FIXED: Several UI polish fixes and Prey progress now resets correctly with the weekly reset.",
        },
    },
    {
        version = "0.8.98",
        date = "April 28, 2026",
        items = {
            "Added the new Alt Score (AS) calculation for weekly character progress.",
            "The Prey Bar should finally be fixed now. Sorry for the noisy back-and-forth while we chased Blizzard's widget behavior.",
            "Great Vault max-reward progress per slot now grants Chronicle XP for Raid, Dungeon, and World / Delves / Prey rows.",
            "Please report bugs in the Curse comments or in the WoW Reddit thread. Thank you for helping test the beta systems.",
        },
    },
    {
        version = "0.8.91",
        date = "April 27, 2026",
        items = {
            "Individual Prey completions now grant Chronicle XP.",
            "Polished Chronicle progress bars so very small progress values no longer create visual edge artifacts.",
        },
    },
    {
        version = "0.8.89",
        date = "April 27, 2026",
        items = {
            "New Chronicle (Beta) tab: earn XP with all your characters and your warband by completing tasks inside Vaultloom. Unlock new ranks and earn badges and character frames that you can show on your character card however you like. If you do not want the system, you can disable it in Options.",
        },
    },
    {
        version = "0.8.28",
        date = "April 26, 2026",
        items = {
            "Added the complete new Fokus tab: build your own quest and task list per character or as a global template, add and remove rows, reorder them, and track only what matters to you.",
            "Added a floating Fokus tracker outside the main window with lock, scale, opacity, font, and frame/text style options.",
            "Fokus can now track Great Vault goals, Delves, Prey, and Profession Knowledge rows alongside normal quest rows.",
            "Added Stat Focus to color and rank important secondary stats for the current class and specialization directly in item tooltips.",
            "Polished the Features and Fokus UI with clearer tooltips, tighter text-only spacing, tracker style options, and consistent arrow icons.",
        },
    },
    {
        version = "0.8.00",
        date = "April 26, 2026",
        items = {
            "Complete Lua core rebuild for a cleaner and more stable Vaultloom base.",
            "Many visual icons, tabs, and menus have been refreshed.",
            "Options now include a new section to show or hide main tabs.",
            "Warband sorting and character visibility now use cleaner dropdown menus.",
            "Added the current logged-in character header across all major views.",
            "Added a new Professions tab for cooldowns and concentration. Estimated times can vary slightly.",
            "Added French and Spanish localizations.",
        },
    },
    {
        version = "0.7.89",
        date = "April 23, 2026",
        items = {
            "Added One-Click Processing for disenchanting, milling, prospecting, and lockpicking.",
            "Added new custom Prey Hunt map icons.",
        },
    },
    {
        version = "0.7.82",
        date = "April 23, 2026",
        items = {
            "Added Profession Knowledge Badges and the new Profession Knowledge section.",
            "Added visual polish and improved Great Vault logic.",
        },
    },
    {
        version = "0.7.65",
        date = "April 22, 2026",
        items = {
            "Added the Spec Switcher Bar, Travel Bar, and Bag Item Level features.",
            "Added support for WoW patch 12.0.5 and new daily and weekly tracking.",
        },
    },
}

local function getNewsEntries()
    if type(L.NEWS_ENTRIES) == "table" and #L.NEWS_ENTRIES > 0 then
        return L.NEWS_ENTRIES
    end

    return DEFAULT_NEWS_ENTRIES
end

function ns:GetNewsCurrentVersion()
    local currentEntry = getNewsEntries()[1]
    return (currentEntry and currentEntry.version) or (self and self.VERSION) or ""
end

local function buildVaultloomNewsBodyText()
    local lines = {}
    local entries = getNewsEntries()
    for index, entry in ipairs(entries) do
        lines[#lines + 1] = string.format(L.NEWS_ENTRY_TITLE or "Changelog %s", tostring(entry.version or "?"))
        lines[#lines + 1] = tostring(entry.date or "")
        for _, item in ipairs(entry.items or {}) do
            lines[#lines + 1] = "- " .. tostring(item)
        end
        if index < #entries then
            lines[#lines + 1] = ""
        end
    end
    return table.concat(lines, "\n")
end

function ns:GetNewsBodyText()
    return buildVaultloomNewsBodyText()
end

function ns:OpenFeaturesPanelFromNews()
    if not (self.UI and self.UI.Toggle) then
        self:Print(L.NEWS_UI_UNAVAILABLE or "Vaultloom UI module is unavailable.")
        return
    end

    local frameShown = self.UI.frame and self.UI.frame:IsShown()
    if not frameShown then
        local okToggle, errToggle = pcall(function()
            self.UI:Toggle()
        end)
        if not okToggle then
            self:Print(string.format(L.NEWS_UI_OPEN_FAILED or "Vaultloom UI failed to open: %s", tostring(errToggle)))
            return
        end
    end

    if self.UI.CloseTransientPanels then
        self.UI:CloseTransientPanels("features")
    end
    self.UI.featuresPanelOpen = true
    if not self.UI.featuresSelectedCategory then
        self.UI.featuresSelectedCategory = (self.GetDefaultFeatureCategory and self:GetDefaultFeatureCategory()) or "progress"
    end
    if self.UI.Refresh then
        self.UI:Refresh()
    end

    if self.newsPopupFrame then
        self.newsPopupFrame:Hide()
    end
end

function ns:EnsureNewsPopup()
    if self.newsPopupFrame then
        return self.newsPopupFrame
    end

    local frame = CreateFrame("Frame", "VaultloomNewsPopup", UIParent, BACKDROP_TEMPLATE)
    frame:SetSize(560, 430)
    frame:SetPoint("CENTER", UIParent, "CENTER", 0, 40)
    frame:SetFrameStrata("DIALOG")
    frame:SetFrameLevel(240)
    frame:SetClampedToScreen(true)
    frame:EnableMouse(true)
    frame:SetMovable(true)
    frame:RegisterForDrag("LeftButton")
    frame:SetScript("OnDragStart", function(selfFrame)
        selfFrame:StartMoving()
    end)
    frame:SetScript("OnDragStop", function(selfFrame)
        selfFrame:StopMovingOrSizing()
    end)
    if frame.SetBackdrop then
        frame:SetBackdrop({
            bgFile = "Interface\\Buttons\\WHITE8X8",
            edgeFile = "Interface\\Buttons\\WHITE8X8",
            edgeSize = 1,
            insets = { left = 1, right = 1, top = 1, bottom = 1 },
        })
        frame:SetBackdropColor(0.05, 0.05, 0.06, 0.96)
        frame:SetBackdropBorderColor(0.68, 0.56, 0.20, 0.92)
    end

    frame.bg = frame:CreateTexture(nil, "BACKGROUND", nil, 1)
    frame.bg:SetPoint("TOPLEFT", 1, -1)
    frame.bg:SetPoint("BOTTOMRIGHT", -1, 1)
    frame.bg:SetTexture("Interface\\Buttons\\WHITE8X8")
    frame.bg:SetColorTexture(0.02, 0.02, 0.03, 0.90)

    frame.overlay = frame:CreateTexture(nil, "BACKGROUND", nil, 2)
    frame.overlay:SetPoint("TOPLEFT", 1, -1)
    frame.overlay:SetPoint("BOTTOMRIGHT", -1, 1)
    frame.overlay:SetTexture("Interface\\Buttons\\WHITE8X8")
    frame.overlay:SetColorTexture(0.16, 0.10, 0.03, 0.08)

    frame:Hide()

    frame.title = frame:CreateFontString(nil, "OVERLAY", "GameFontNormalLarge")
    frame.title:SetPoint("TOPLEFT", 18, -16)
    frame.title:SetPoint("TOPRIGHT", -18, -16)
    frame.title:SetJustifyH("LEFT")
    frame.title:SetTextColor(1.00, 0.85, 0.22)
    frame.title:SetText(L.NEWS_POPUP_TITLE or "Vaultloom What's New")

    frame.subtitle = frame:CreateFontString(nil, "OVERLAY", "GameFontHighlightSmall")
    frame.subtitle:SetPoint("TOPLEFT", frame.title, "BOTTOMLEFT", 0, -8)
    frame.subtitle:SetPoint("TOPRIGHT", -18, 0)
    frame.subtitle:SetJustifyH("LEFT")
    frame.subtitle:SetText(L.NEWS_POPUP_SUBTITLE or "Current update plus recent patch notes.")

    frame.body = frame:CreateFontString(nil, "OVERLAY", "GameFontHighlightSmall")
    frame.body:SetPoint("TOPLEFT", frame.subtitle, "BOTTOMLEFT", 0, -16)
    frame.body:SetPoint("TOPRIGHT", -22, 0)
    frame.body:SetJustifyH("LEFT")
    frame.body:SetJustifyV("TOP")
    frame.body:SetWordWrap(true)
    frame.body:SetText(buildVaultloomNewsBodyText())

    frame.hint = frame:CreateFontString(nil, "OVERLAY", "GameFontDisableSmall")
    frame.hint:SetPoint("BOTTOMLEFT", 18, 48)
    frame.hint:SetPoint("BOTTOMRIGHT", -18, 48)
    frame.hint:SetJustifyH("LEFT")
    frame.hint:SetText(L.NEWS_POPUP_HINT or "Open /vl and view Options to see this again.")

    frame.closeButton = CreateFrame("Button", nil, frame, "UIPanelButtonTemplate")
    frame.closeButton:SetSize(96, 24)
    frame.closeButton:SetPoint("BOTTOMRIGHT", -18, 14)
    frame.closeButton:SetText(L.CLOSE or "Close")
    frame.closeButton:SetScript("OnClick", function()
        frame:Hide()
    end)

    frame.featuresButton = CreateFrame("Button", nil, frame, "UIPanelButtonTemplate")
    frame.featuresButton:SetSize(118, 24)
    frame.featuresButton:SetPoint("RIGHT", frame.closeButton, "LEFT", -8, 0)
    frame.featuresButton:SetText(L.NEWS_OPEN_FEATURES or "Open Features")
    frame.featuresButton:SetScript("OnClick", function()
        ns:OpenFeaturesPanelFromNews()
    end)

    self.newsPopupFrame = frame
    return frame
end

function ns:ShowNewsPopup()
    if self.UI and self.UI.OpenSettingsPanel then
        local okSettings, openedSettings = pcall(function()
            return self.UI:OpenSettingsPanel()
        end)
        if okSettings and openedSettings then
            if self.db and self.db.ui then
                self.db.ui.newsSeenVersion = self:GetNewsCurrentVersion()
            end
            return
        end
    end

    local frame = self:EnsureNewsPopup()
    frame.title:SetText(string.format(L.NEWS_CHANGELOG_TITLE or "Vaultloom Changelog %s", tostring(self.VERSION or self:GetNewsCurrentVersion())))
    frame.body:SetText(buildVaultloomNewsBodyText())
    frame:Show()
    frame:Raise()

    if self.db and self.db.ui then
        self.db.ui.newsSeenVersion = self:GetNewsCurrentVersion()
    end
end
