-- Raid-Notes Addon
-- 4-screen workflow: Expansions -> Raids -> Bosses -> Notes
-- Usage: /raidnotes or /rn - Open main window

local addonName, RaidNotes = ...

-- Initialize SavedVariables
RaidNotesDB = RaidNotesDB or {}
RaidNotes.notes = RaidNotesDB

-- Raid shortcuts for quick access
RaidNotes.raidShortcuts = {
    -- Classic
    ["mc"] = {expansion = "Classic", raid = "Molten Core"},
    ["bwl"] = {expansion = "Classic", raid = "Blackwing Lair"},
    ["zg"] = {expansion = "Classic", raid = "Zul'Gurub"},
    ["aq20"] = {expansion = "Classic", raid = "Ruins of Ahn'Qiraj"},
    ["aq40"] = {expansion = "Classic", raid = "Temple of Ahn'Qiraj"},
    ["ony"] = {expansion = "Classic", raid = "Onyxia's Lair"},
    ["naxx"] = {expansion = "Classic", raid = "Naxxramas"},
    
    -- TBC
    ["kara"] = {expansion = "The Burning Crusade", raid = "Karazhan"},
    ["gruul"] = {expansion = "The Burning Crusade", raid = "Gruul's Lair"},
    ["mag"] = {expansion = "The Burning Crusade", raid = "Magtheridon's Lair"},
    ["ssc"] = {expansion = "The Burning Crusade", raid = "Serpentshrine Cavern"},
    ["tk"] = {expansion = "The Burning Crusade", raid = "Tempest Keep"},
    ["hyjal"] = {expansion = "The Burning Crusade", raid = "Hyjal Summit"},
    ["bt"] = {expansion = "The Burning Crusade", raid = "Black Temple"},
    ["swp"] = {expansion = "The Burning Crusade", raid = "Sunwell Plateau"},
    
    -- WotLK
    ["voa"] = {expansion = "Wrath of the Lich King", raid = "Vault of Archavon"},
    ["os"] = {expansion = "Wrath of the Lich King", raid = "Obsidian Sanctum"},
    ["eoe"] = {expansion = "Wrath of the Lich King", raid = "Eye of Eternity"},
    ["uld"] = {expansion = "Wrath of the Lich King", raid = "Ulduar"},
    ["toc"] = {expansion = "Wrath of the Lich King", raid = "Trial of the Crusader"},
    ["icc"] = {expansion = "Wrath of the Lich King", raid = "Icecrown Citadel"},
    ["rs"] = {expansion = "Wrath of the Lich King", raid = "Ruby Sanctum"},
    
    -- Cataclysm
    ["bwd"] = {expansion = "Cataclysm", raid = "Blackwing Descent"},
    ["bot"] = {expansion = "Cataclysm", raid = "The Bastion of Twilight"},
    ["totfw"] = {expansion = "Cataclysm", raid = "Throne of the Four Winds"},
    ["bh"] = {expansion = "Cataclysm", raid = "Baradin Hold"},
    ["fl"] = {expansion = "Cataclysm", raid = "Firelands"},
    ["ds"] = {expansion = "Cataclysm", raid = "Dragon Soul"},
    
    -- MoP
    ["msv"] = {expansion = "Mists of Pandaria", raid = "Mogu'shan Vaults"},
    ["hof"] = {expansion = "Mists of Pandaria", raid = "Heart of Fear"},
    ["tes"] = {expansion = "Mists of Pandaria", raid = "Terrace of Endless Spring"},
    ["tot"] = {expansion = "Mists of Pandaria", raid = "Throne of Thunder"},
    ["soo"] = {expansion = "Mists of Pandaria", raid = "Siege of Orgrimmar"}
}

-- Expansions and raids data (in release order)
RaidNotes.expansionOrder = {"Classic", "The Burning Crusade", "Wrath of the Lich King", "Cataclysm", "Mists of Pandaria"}
RaidNotes.expansions = {
    ["Classic"] = {
        "Molten Core",          -- Nov 2004
        "Onyxia's Lair",        -- Nov 2004  
        "Blackwing Lair",       -- Feb 2005
        "Zul'Gurub",            -- Apr 2005
        "Ruins of Ahn'Qiraj",   -- Jan 2006
        "Temple of Ahn'Qiraj",  -- Jan 2006
        "Naxxramas"             -- Jun 2006
    },
    ["The Burning Crusade"] = {
        "Karazhan",             -- Jan 2007
        "Gruul's Lair",         -- Jan 2007
        "Magtheridon's Lair",   -- Jan 2007
        "Serpentshrine Cavern", -- Jan 2007
        "Tempest Keep",         -- Jan 2007
        "Hyjal Summit",         -- May 2007
        "Black Temple",         -- May 2007
        "Sunwell Plateau"       -- Mar 2008
    },
    ["Wrath of the Lich King"] = {
        "Vault of Archavon",    -- Nov 2008
        "Obsidian Sanctum",     -- Nov 2008
        "Naxxramas",            -- Nov 2008
        "Eye of Eternity",      -- Nov 2008
        "Ulduar",               -- Apr 2009
        "Trial of the Crusader", -- Aug 2009
        "Onyxia's Lair",        -- Sep 2009
        "Icecrown Citadel",     -- Dec 2009
        "Ruby Sanctum"          -- Jun 2010
    },
    ["Cataclysm"] = {
        "Blackwing Descent",    -- Dec 2010
        "The Bastion of Twilight", -- Dec 2010
        "Throne of the Four Winds", -- Dec 2010
        "Baradin Hold",         -- Dec 2010
        "Firelands",            -- Jun 2011
        "Dragon Soul"           -- Nov 2011
    },
    ["Mists of Pandaria"] = {
        "Mogu'shan Vaults",     -- Sep 2012
        "Heart of Fear",        -- Nov 2012
        "Terrace of Endless Spring", -- Nov 2012
        "Throne of Thunder",    -- Mar 2013
        "Siege of Orgrimmar"    -- Sep 2013
    }
}

-- Bosses per raid
RaidNotes.bosses = {
    ["Onyxia's Lair"] = {"Onyxia"},
    ["Molten Core"] = {"Lucifron", "Magmadar", "Gehennas", "Garr", "Baron Geddon", "Shazzrah", "Sulfuron Harbinger", "Golemagg", "Majordomo Executus", "Ragnaros"},
    ["Blackwing Lair"] = {"Razorgore", "Vaelastrasz", "Broodlord Lashlayer", "Firemaw", "Ebonroc", "Flamegor", "Chromaggus", "Nefarian"},
    ["Zul'Gurub"] = {"Jeklik", "Venoxis", "Mar'li", "Mandokir", "Gahz'ranka", "Thekal", "Arlokk", "Jin'do", "Hakkar"},
    ["Ruins of Ahn'Qiraj"] = {"Kurinnaxx", "General Rajaxx", "Moam", "Buru", "Ayamiss", "Ossirian"},
    ["Temple of Ahn'Qiraj"] = {"The Prophet Skeram", "Bug Trio", "Battleguard Sartura", "Fankriss", "Viscidus", "Princess Huhuran", "Twin Emperors", "Ouro", "C'Thun"},
    ["Naxxramas"] = {"Anub'Rekhan", "Grand Widow Faerlina", "Maexxna", "Noth", "Heigan", "Loatheb", "Instructor Razuvious", "Gothik", "The Four Horsemen", "Patchwerk", "Grobbulus", "Gluth", "Thaddius", "Sapphiron", "Kel'Thuzad"},
    
    -- TBC Raids
    ["Karazhan"] = {"Attumen", "Moroes", "Maiden of Virtue", "Opera Event", "The Curator", "Terestian Illhoof", "Shade of Aran", "Netherspite", "Chess Event", "Prince Malchezaar"},
    ["Gruul's Lair"] = {"High King Maulgar", "Gruul the Dragonkiller"},
    ["Magtheridon's Lair"] = {"Magtheridon"},
    ["Serpentshrine Cavern"] = {"Hydross", "The Lurker Below", "Leotheras", "Fathom-Lord Karathress", "Morogrim Tidewalker", "Lady Vashj"},
    ["Tempest Keep"] = {"Al'ar", "Void Reaver", "High Astromancer Solarian", "Kael'thas Sunstrider"},
    ["Hyjal Summit"] = {"Rage Winterchill", "Anetheron", "Kaz'rogal", "Azgalor", "Archimonde"},
    ["Black Temple"] = {"High Warlord Naj'entus", "Supremus", "Shade of Akama", "Teron Gorefiend", "Gurtogg Bloodboil", "Reliquary of Souls", "Mother Shahraz", "Illidari Council", "Illidan Stormrage"},
    ["Sunwell Plateau"] = {"Kalecgos", "Brutallus", "Felmyst", "Eredar Twins", "M'uru", "Kil'jaeden"},
    
    -- WotLK Raids
    ["Vault of Archavon"] = {"Archavon", "Emalon", "Koralon", "Toravon"},
    ["Obsidian Sanctum"] = {"Sartharion"},
    ["Eye of Eternity"] = {"Malygos"},
    ["Ulduar"] = {"Flame Leviathan", "Ignis", "Razorscale", "XT-002", "Assembly of Iron", "Kologarn", "Auriaya", "Hodir", "Thorim", "Freya", "Mimiron", "General Vezax", "Yogg-Saron", "Algalon"},
    ["Trial of the Crusader"] = {"Northrend Beasts", "Lord Jaraxxus", "Faction Champions", "Twin Val'kyr", "Anub'arak"},
    ["Icecrown Citadel"] = {"Lord Marrowgar", "Lady Deathwhisper", "Gunship Battle", "Deathbringer Saurfang", "Festergut", "Rotface", "Professor Putricide", "Blood Prince Council", "Blood-Queen Lana'thel", "Valithria Dreamwalker", "Sindragosa", "The Lich King"},
    ["Ruby Sanctum"] = {"Halion"},
    
    -- Cataclysm Raids
    ["Blackwing Descent"] = {"Magmaw", "Omnotron Defense System", "Maloriak", "Atramedes", "Chimaeron", "Nefarian"},
    ["The Bastion of Twilight"] = {"Halfus Wyrmbreaker", "Valiona and Theralion", "Ascendant Council", "Cho'gall", "Sinestra"},
    ["Throne of the Four Winds"] = {"Conclave of Wind", "Al'Akir"},
    ["Baradin Hold"] = {"Argaloth", "Occu'thar", "Alizabal"},
    ["Firelands"] = {"Shannox", "Lord Rhyolith", "Beth'tilac", "Alysrazor", "Baleroc", "Majordomo Staghelm", "Ragnaros"},
    ["Dragon Soul"] = {"Morchok", "Warlord Zon'ozz", "Yor'sahj", "Hagara", "Ultraxion", "Warmaster Blackhorn", "Spine of Deathwing", "Madness of Deathwing"},
    
    -- Mists of Pandaria Raids
    ["Mogu'shan Vaults"] = {"The Stone Guard", "Feng the Accursed", "Gara'jal", "The Spirit Kings", "Elegon", "Will of the Emperor"},
    ["Heart of Fear"] = {"Imperial Vizier Zor'lok", "Blade Lord Ta'yak", "Garalon", "Wind Lord Mel'jarak", "Amber-Shaper Un'sok", "Grand Empress Shek'zeer"},
    ["Terrace of Endless Spring"] = {"Protectors of the Endless", "Tsulong", "Lei Shi", "Sha of Fear"},
    ["Throne of Thunder"] = {"Jin'rokh", "Horridon", "Council of Elders", "Tortos", "Megaera", "Ji-Kun", "Durumu", "Primordius", "Dark Animus", "Iron Qon", "Twin Consorts", "Lei Shen", "Ra-den"},
    ["Siege of Orgrimmar"] = {"Immerseus", "The Fallen Protectors", "Norushen", "Sha of Pride", "Galakras", "Iron Juggernaut", "Kor'kron Dark Shaman", "General Nazgrim", "Malkorok", "Spoils of Pandaria", "Thok", "Siegecrafter Blackfuse", "Paragons of the Klaxxi", "Garrosh Hellscream"}
}

-- Create main frame
function RaidNotes:CreateMainFrame()
    local frame = CreateFrame("Frame", "RaidNotesFrame", UIParent, "BackdropTemplate")
    frame:SetSize(500, 400)
    frame:SetPoint("CENTER")
    frame:SetBackdrop({
        bgFile = "Interface/Tooltips/UI-Tooltip-Background",
        edgeFile = "Interface/Tooltips/UI-Tooltip-Border",
        tile = true, tileSize = 16, edgeSize = 16,
        insets = {left = 4, right = 4, top = 4, bottom = 4}
    })
    frame:SetBackdropColor(0,0,0,0.8)
    frame:EnableMouse(true)
    frame:SetMovable(true)
    frame:RegisterForDrag("LeftButton")
    frame:SetScript("OnDragStart", frame.StartMoving)
    frame:SetScript("OnDragStop", frame.StopMovingOrSizing)

    -- Title
    local title = frame:CreateFontString(nil, "OVERLAY", "GameFontNormalLarge")
    title:SetPoint("TOP", frame, "TOP", 0, -10)
    title:SetText("Raid-Notes")
    frame.title = title

    -- Close button
    local closeBtn = CreateFrame("Button", nil, frame, "UIPanelCloseButton")
    closeBtn:SetPoint("TOPRIGHT", frame, "TOPRIGHT", -5, -5)

    frame.buttons = {}
    frame.noteWidgets = {}
    frame.currentExpansion = nil
    frame.currentRaid = nil
    frame.currentBoss = nil
    return frame
end

-- Create minimap button
function RaidNotes:CreateMinimapButton()
    local button = CreateFrame("Button", "RaidNotesMinimapButton", Minimap)
    button:SetSize(32, 32)
    button:SetFrameStrata("MEDIUM")
    button:SetFrameLevel(8)
    button:RegisterForClicks("AnyUp")
    button:RegisterForDrag("LeftButton")
    button:SetMovable(true)
    button:EnableMouse(true)
    
    -- Set the icon texture
    local icon = button:CreateTexture(nil, "BACKGROUND")
    icon:SetSize(20, 20)
    icon:SetPoint("CENTER", 0, 0)
    icon:SetTexture("Interface\\AddOns\\Raid-Notes\\images\\icon")
    button.icon = icon
    
    -- Create border
    local overlay = button:CreateTexture(nil, "OVERLAY")
    overlay:SetSize(53, 53)
    overlay:SetTexture("Interface\\Minimap\\MiniMap-TrackingBorder")
    overlay:SetPoint("TOPLEFT")
    
    -- Position on minimap
    button:SetPoint("TOPLEFT", Minimap, "TOPLEFT", 52, -52)
    
    -- Click handler
    button:SetScript("OnClick", function(self, button)
        if button == "LeftButton" then
            RaidNotes:ShowMainWindow()
        elseif button == "RightButton" then
            -- Right-click for quick menu (future feature)
        end
    end)
    
    -- Drag functionality for repositioning
    button:SetScript("OnDragStart", function(self)
        self:LockHighlight()
        self:SetScript("OnUpdate", RaidNotes.UpdateMinimapButton)
    end)
    
    button:SetScript("OnDragStop", function(self)
        self:UnlockHighlight()
        self:SetScript("OnUpdate", nil)
    end)
    
    -- Tooltip
    button:SetScript("OnEnter", function(self)
        GameTooltip:SetOwner(self, "ANCHOR_LEFT")
        GameTooltip:SetText("Raid-Notes", 1, 1, 1)
        GameTooltip:AddLine("Left-click: Open addon", 0.8, 0.8, 0.8)
        GameTooltip:AddLine("Drag: Reposition button", 0.8, 0.8, 0.8)
        GameTooltip:Show()
    end)
    
    button:SetScript("OnLeave", function(self)
        GameTooltip:Hide()
    end)
    
    return button
end

-- Update minimap button position during drag
function RaidNotes:UpdateMinimapButton()
    local mxpos, mypos = Minimap:GetCenter()
    local px, py = GetCursorPosition()
    local scale = Minimap:GetEffectiveScale()
    px, py = px / scale, py / scale
    
    local angle = math.atan2(py - mypos, px - mxpos)
    local x = math.cos(angle) * 80
    local y = math.sin(angle) * 80
    
    RaidNotesMinimapButton:SetPoint("CENTER", Minimap, "CENTER", x, y)
end

-- Clear all buttons and widgets
function RaidNotes:ClearAll()
    local frame = RaidNotesFrame
    if frame.buttons then
        for _, btn in ipairs(frame.buttons) do
            btn:Hide()
            btn:SetParent(nil)
        end
        frame.buttons = {}
    end
    if frame.noteWidgets then
        for _, widget in ipairs(frame.noteWidgets) do
            widget:Hide()
            widget:SetParent(nil)
        end
        frame.noteWidgets = {}
    end
end

-- Screen 1: Show expansion list
function RaidNotes:ShowExpansions()
    local frame = RaidNotesFrame
    self:ClearAll()
    frame.title:SetText("Raid-Notes - Select Expansion")
    
    local y = -50
    for i, expansion in ipairs(self.expansionOrder) do
        local btn = CreateFrame("Button", nil, frame, "UIPanelButtonTemplate")
        btn:SetSize(460, 30)
        btn:SetPoint("TOP", frame, "TOP", 0, y)
        btn:SetText(expansion)
        btn:SetScript("OnClick", function()
            frame.currentExpansion = expansion
            self:ShowRaids(expansion)
        end)
        table.insert(frame.buttons, btn)
        y = y - 35
    end
end

-- Screen 2: Show raid list for expansion
function RaidNotes:ShowRaids(expansion)
    local frame = RaidNotesFrame
    self:ClearAll()
    frame.title:SetText("Raid-Notes - " .. expansion)
    
    -- Back button
    local backBtn = CreateFrame("Button", nil, frame, "UIPanelButtonTemplate")
    backBtn:SetSize(460, 30)
    backBtn:SetPoint("TOP", frame, "TOP", 0, -50)
    backBtn:SetText("< Back to Expansions")
    backBtn:SetScript("OnClick", function()
        frame.currentExpansion = nil
        self:ShowExpansions()
    end)
    table.insert(frame.buttons, backBtn)
    
    local y = -90
    for _, raid in ipairs(self.expansions[expansion]) do
        local btn = CreateFrame("Button", nil, frame, "UIPanelButtonTemplate")
        btn:SetSize(460, 30)
        btn:SetPoint("TOP", frame, "TOP", 0, y)
        btn:SetText(raid)
        btn:SetScript("OnClick", function()
            frame.currentRaid = raid
            self:ShowBosses(expansion, raid)
        end)
        table.insert(frame.buttons, btn)
        y = y - 35
    end
end

-- Screen 3: Show boss list for raid
function RaidNotes:ShowBosses(expansion, raid)
    local frame = RaidNotesFrame
    self:ClearAll()
    frame.title:SetText("Raid-Notes - " .. raid)
    
    -- Back button
    local backBtn = CreateFrame("Button", nil, frame, "UIPanelButtonTemplate")
    backBtn:SetSize(460, 30)
    backBtn:SetPoint("TOP", frame, "TOP", 0, -50)
    backBtn:SetText("< Back to " .. expansion)
    backBtn:SetScript("OnClick", function()
        frame.currentRaid = nil
        self:ShowRaids(expansion)
    end)
    table.insert(frame.buttons, backBtn)
    
    local bosses = self.bosses[raid] or {}
    local y = -90
    local col = 0
    for _, boss in ipairs(bosses) do
        local btn = CreateFrame("Button", nil, frame, "UIPanelButtonTemplate")
        btn:SetSize(220, 30)
        btn:SetPoint("TOPLEFT", frame, "TOPLEFT", 20 + col * 240, y)
        btn:SetText(boss)
        btn:SetScript("OnClick", function()
            frame.currentBoss = boss
            self:ShowBossNotes(expansion, raid, boss)
        end)
        table.insert(frame.buttons, btn)
        
        col = col + 1
        if col >= 2 then
            col = 0
            y = y - 35
        end
    end
end

-- Screen 4: Show notes screen for boss
function RaidNotes:ShowBossNotes(expansion, raid, boss)
    local frame = RaidNotesFrame
    self:ClearAll()
    frame.title:SetText("Raid-Notes - " .. boss)
    
    -- Back button
    local backBtn = CreateFrame("Button", nil, frame, "UIPanelButtonTemplate")
    backBtn:SetSize(460, 30)
    backBtn:SetPoint("TOP", frame, "TOP", 0, -50)
    backBtn:SetText("< Back to " .. raid)
    backBtn:SetScript("OnClick", function()
        frame.currentBoss = nil
        self:ShowBosses(expansion, raid)
    end)
    table.insert(frame.buttons, backBtn)
    
    -- Notes text field (proper multi-line with text wrapping)
    local noteFrame = CreateFrame("Frame", nil, frame, "BackdropTemplate")
    noteFrame:SetSize(460, 125)
    noteFrame:SetPoint("TOP", frame, "TOP", 0, -90)
    noteFrame:SetBackdrop({
        bgFile = "Interface/Tooltips/UI-Tooltip-Background",
        edgeFile = "Interface/Tooltips/UI-Tooltip-Border",
        tile = true, tileSize = 16, edgeSize = 16,
        insets = {left = 4, right = 4, top = 4, bottom = 4}
    })
    noteFrame:SetBackdropColor(0.1, 0.1, 0.1, 0.8)
    noteFrame:SetBackdropBorderColor(0.6, 0.6, 0.6, 1)
    
    local noteBox = CreateFrame("EditBox", nil, noteFrame)
    noteBox:SetSize(450, 120)
    noteBox:SetPoint("CENTER", noteFrame, "CENTER", 0, 0)
    noteBox:SetMultiLine(true)
    noteBox:SetAutoFocus(false)
    noteBox:SetFontObject("GameFontHighlight")
    noteBox:SetTextColor(1, 1, 1, 1)
    noteBox:SetMaxLetters(255)
    noteBox:EnableMouse(true)
    noteBox:EnableKeyboard(true)
    noteBox:SetFocus()
    noteBox:SetCursorPosition(0)
    
    -- Make the frame clickable to focus the editbox
    noteFrame:EnableMouse(true)
    noteFrame:SetScript("OnMouseDown", function()
        noteBox:SetFocus()
    end)
    
    noteBox:SetScript("OnEditFocusGained", function(self)
        self:SetTextColor(1, 1, 1, 1)
    end)
    
    noteBox:SetScript("OnEditFocusLost", function(self)
        self:SetTextColor(0.8, 0.8, 0.8, 1)
    end)
    
    noteBox:SetScript("OnEscapePressed", function(self) 
        self:ClearFocus() 
    end)
    
    noteBox:SetScript("OnEnterPressed", function(self) 
        -- Insert newline at cursor position
        local text = self:GetText()
        local cursorPos = self:GetCursorPosition()
        if string.len(text) < 254 then -- Leave room for the newline
            local newText = string.sub(text, 1, cursorPos) .. "\n" .. string.sub(text, cursorPos + 1)
            self:SetText(newText)
            self:SetCursorPosition(cursorPos + 1)
        end
    end)
    
    table.insert(frame.noteWidgets, noteFrame)
    table.insert(frame.noteWidgets, noteBox)
    
    -- Character counter
    local charCount = frame:CreateFontString(nil, "OVERLAY", "GameFontNormal")
    charCount:SetPoint("TOPRIGHT", noteBox, "BOTTOMRIGHT", 0, -5)
    charCount:SetText("0/255")
    table.insert(frame.noteWidgets, charCount)
    
    -- Load existing note
    local noteKey = raid .. "_" .. boss
    noteBox:SetText(self.notes[noteKey] or "")
    
    -- Update character counter
    local function updateCharCount()
        local text = noteBox:GetText()
        local len = string.len(text)
        charCount:SetText(len .. "/255")
        if len > 255 then
            charCount:SetTextColor(1, 0, 0) -- Red if over limit
        else
            charCount:SetTextColor(1, 1, 1) -- White if under limit
        end
    end
    
    -- Save note and update counter when text changes
    noteBox:SetScript("OnTextChanged", function(self)
        RaidNotes.notes[noteKey] = self:GetText()
        updateCharCount()
    end)
    
    -- Initial character count update
    updateCharCount()
    
    table.insert(frame.noteWidgets, noteBox)
    
    -- Raid Warning checkbox
    local rwCheck = CreateFrame("CheckButton", nil, frame, "UICheckButtonTemplate")
    rwCheck:SetPoint("BOTTOMLEFT", frame, "BOTTOMLEFT", 20, 40)
    rwCheck.text:SetText("Raid Warning")
    rwCheck:SetSize(20, 20)
    table.insert(frame.noteWidgets, rwCheck)
    
    -- Announce button
    local announceBtn = CreateFrame("Button", nil, frame, "UIPanelButtonTemplate")
    announceBtn:SetSize(120, 30)
    announceBtn:SetPoint("BOTTOM", frame, "BOTTOM", 0, 20)
    announceBtn:SetText("Announce")
    announceBtn:SetScript("OnClick", function()
        local note = noteBox:GetText()
        if note and note ~= "" then
            -- Remove newlines and format for chat
            local chatText = string.gsub(note, "\n", " ")
            
            if string.len(chatText) > 255 then
                print("Note is too long (" .. string.len(chatText) .. " chars). Max 255 for chat.")
                return
            end
            
            if rwCheck:GetChecked() then
                SendChatMessage(chatText, "RAID_WARNING")
                print("Sent raid warning: " .. chatText)
            else
                SendChatMessage(chatText, "RAID")
                print("Sent raid message: " .. chatText)
            end
        else
            print("No note to announce!")
        end
    end)
    table.insert(frame.noteWidgets, announceBtn)
    
    -- Copy button
    local copyBtn = CreateFrame("Button", nil, frame, "UIPanelButtonTemplate")
    copyBtn:SetSize(80, 30)
    copyBtn:SetPoint("BOTTOMRIGHT", frame, "BOTTOMRIGHT", -20, 20)
    copyBtn:SetText("Copy")
    copyBtn:SetScript("OnClick", function()
        local text = noteBox:GetText()
        if text and text ~= "" then
            noteBox:SetFocus()
            noteBox:HighlightText(0, string.len(text))
            print("Text selected! Press Ctrl+C to copy to clipboard.")
        else
            print("No text to copy!")
        end
    end)
    table.insert(frame.noteWidgets, copyBtn)
end

-- Main show function
function RaidNotes:ShowMainWindow()
    if not RaidNotesFrame then
        RaidNotesFrame = self:CreateMainFrame()
    end
    RaidNotesFrame:Show()
    self:ShowExpansions()
end

-- Slash command registration
SLASH_RAIDNOTES1 = "/raidnotes"
SLASH_RAIDNOTES2 = "/rn"
SlashCmdList["RAIDNOTES"] = function(msg, editbox)
    
    -- Check if arguments were provided
    if msg and msg ~= "" then
        local args = {}
        for word in string.gmatch(msg, "%S+") do
            table.insert(args, string.lower(word))
        end
        
        if #args == 1 then
            -- Single argument - check if it's a raid shortcut
            local shortcut = args[1]
            local raidInfo = RaidNotes.raidShortcuts[shortcut]
            
            if raidInfo then
                -- Open directly to the specified raid's boss list
                RaidNotes:ShowMainWindow()
                local frame = RaidNotesFrame
                frame.currentExpansion = raidInfo.expansion
                frame.currentRaid = raidInfo.raid
                RaidNotes:ShowBosses(raidInfo.expansion, raidInfo.raid)
            else
                -- Show available shortcuts
                print("Unknown raid shortcut: " .. shortcut)
                print("Available shortcuts:")
                print("Classic: mc, bwl, zg, aq20, aq40, ony, naxx")
                print("TBC: kara, gruul, mag, ssc, tk, hyjal, bt, swp")
                print("WotLK: voa, os, eoe, uld, toc, icc, rs")
                print("Cataclysm: bwd, bot, totfw, bh, fl, ds")
                print("MoP: msv, hof, tes, tot, soo")
                print("Or use: /rn [shortcut] [boss] announce (e.g., /rn mc ragnaros announce)")
                print("Or use: /rn [expansion] [raid] [boss] (e.g., /rn classic mc ragnaros)")
            end
        elseif #args == 2 then
            -- Two arguments - expansion and raid
            local expansionArg = args[1]
            local raidArg = args[2]
            
            -- Try to match expansion
            local expansion = nil
            for _, exp in ipairs(RaidNotes.expansionOrder) do
                if string.lower(exp):find(expansionArg) or 
                   (expansionArg == "classic" and exp == "Classic") or
                   (expansionArg == "tbc" and exp == "The Burning Crusade") or
                   (expansionArg == "bc" and exp == "The Burning Crusade") or
                   (expansionArg == "wotlk" and exp == "Wrath of the Lich King") or
                   (expansionArg == "wrath" and exp == "Wrath of the Lich King") or
                   (expansionArg == "cata" and exp == "Cataclysm") or
                   (expansionArg == "mop" and exp == "Mists of Pandaria") then
                    expansion = exp
                    break
                end
            end
            
            if expansion then
                -- Try to match raid within that expansion
                local raid = nil
                for _, raidName in ipairs(RaidNotes.expansions[expansion]) do
                    if string.lower(raidName):find(raidArg) or
                       (raidArg == "mc" and raidName == "Molten Core") or
                       (raidArg == "bwl" and raidName == "Blackwing Lair") or
                       (raidArg == "aq20" and raidName == "Ruins of Ahn'Qiraj") or
                       (raidArg == "aq40" and raidName == "Temple of Ahn'Qiraj") then
                        raid = raidName
                        break
                    end
                end
                
                if raid then
                    -- Open directly to the boss list
                    RaidNotes:ShowMainWindow()
                    local frame = RaidNotesFrame
                    frame.currentExpansion = expansion
                    frame.currentRaid = raid
                    RaidNotes:ShowBosses(expansion, raid)
                else
                    print("Raid not found in " .. expansion)
                    print("Available raids in " .. expansion .. ":")
                    for _, raidName in ipairs(RaidNotes.expansions[expansion]) do
                        print("  " .. raidName)
                    end
                end
            else
                print("Expansion not found: " .. expansionArg)
                print("Available expansions: classic, tbc/bc, wotlk/wrath, cata, mop")
            end
        elseif #args == 3 then
            -- Three arguments - shortcut/expansion, raid, boss/announce
            local arg1 = args[1]
            local arg2 = args[2]
            local arg3 = args[3]
            
            -- Check if this is a shortcut + boss + announce format (e.g., /rn mc ragnaros announce)
            local raidInfo = RaidNotes.raidShortcuts[arg1]
            if raidInfo and (arg3 == "announce" or arg3 == "ann") then
                -- Find the boss
                local boss = nil
                for _, bossName in ipairs(RaidNotes.bosses[raidInfo.raid] or {}) do
                    if string.lower(bossName):find(string.lower(arg2)) then
                        boss = bossName
                        break
                    end
                end
                
                if boss then
                    local noteKey = raidInfo.raid .. "_" .. boss
                    local note = RaidNotes.notes[noteKey]
                    if note and note ~= "" then
                        SendChatMessage("[" .. boss .. "] " .. note, "RAID")
                        print("Announced " .. boss .. " strategy to raid chat")
                    else
                        print("No notes found for " .. boss .. " in " .. raidInfo.raid)
                    end
                else
                    print("Boss not found: " .. arg2 .. " in " .. raidInfo.raid)
                    print("Available bosses:")
                    for _, bossName in ipairs(RaidNotes.bosses[raidInfo.raid] or {}) do
                        print("  " .. bossName)
                    end
                end
            else
                -- Try expansion + raid + boss format (e.g., /rn classic mc ragnaros)
                local expansion = nil
                for _, exp in ipairs(RaidNotes.expansionOrder) do
                    if string.lower(exp):find(arg1) or 
                       (arg1 == "classic" and exp == "Classic") or
                       (arg1 == "tbc" and exp == "The Burning Crusade") or
                       (arg1 == "bc" and exp == "The Burning Crusade") or
                       (arg1 == "wotlk" and exp == "Wrath of the Lich King") or
                       (arg1 == "wrath" and exp == "Wrath of the Lich King") or
                       (arg1 == "cata" and exp == "Cataclysm") or
                       (arg1 == "mop" and exp == "Mists of Pandaria") then
                        expansion = exp
                        break
                    end
                end
                
                if expansion then
                    local raid = nil
                    for _, raidName in ipairs(RaidNotes.expansions[expansion]) do
                        if string.lower(raidName):find(arg2) or
                           (arg2 == "mc" and raidName == "Molten Core") or
                           (arg2 == "bwl" and raidName == "Blackwing Lair") or
                           (arg2 == "aq20" and raidName == "Ruins of Ahn'Qiraj") or
                           (arg2 == "aq40" and raidName == "Temple of Ahn'Qiraj") then
                            raid = raidName
                            break
                        end
                    end
                    
                    if raid then
                        local boss = nil
                        for _, bossName in ipairs(RaidNotes.bosses[raid] or {}) do
                            if string.lower(bossName):find(string.lower(arg3)) then
                                boss = bossName
                                break
                            end
                        end
                        
                        if boss then
                            -- Open directly to the boss notes
                            RaidNotes:ShowMainWindow()
                            local frame = RaidNotesFrame
                            frame.currentExpansion = expansion
                            frame.currentRaid = raid
                            frame.currentBoss = boss
                            RaidNotes:ShowBossNotes(expansion, raid, boss)
                        else
                            print("Boss not found: " .. arg3 .. " in " .. raid)
                        end
                    else
                        print("Raid not found: " .. arg2 .. " in " .. expansion)
                    end
                else
                    print("Invalid format. Use: /rn [shortcut] [boss] announce or /rn [expansion] [raid] [boss]")
                end
            end
        else
            print("Usage: /rn [shortcut] or /rn [expansion] [raid]")
            print("Examples: /rn mc, /rn classic molten, /rn tbc kara")
        end
    else
        -- No argument, open normally
        RaidNotes:ShowMainWindow()
    end
end

-- Event frame for SavedVariables initialization
local eventFrame = CreateFrame("Frame")
eventFrame:RegisterEvent("ADDON_LOADED")
eventFrame:RegisterEvent("PLAYER_LOGOUT")
eventFrame:SetScript("OnEvent", function(self, event, addonName)
    if event == "ADDON_LOADED" and addonName == "Raid-Notes" then
        -- Initialize SavedVariables
        RaidNotesDB = RaidNotesDB or {}
        RaidNotes.notes = RaidNotesDB
        
        -- Create minimap button
        RaidNotes:CreateMinimapButton()
    elseif event == "PLAYER_LOGOUT" then
        -- Ensure data is saved (automatic with SavedVariables)
    end
end)
