-- ============================================================
-- RealNibba.Routes.lua  - Routes Window + Create Route
-- Layout: WoW-native internal title bar, consistent spacing
-- WIN_W=320, WIN_H=440
-- ============================================================
local P = RNPack

local BPAD  = P.BPAD  or 14
local GAP   = P.GAP   or 6
local GAP_S = P.GAP_S or 3
local BTN_H = P.BTN_H or 22
local LBL_H = P.LBL_H or 14
local WIN_W = P.WIN_W or 320
local WIN_H = 440

-- Shared locals for show/hide between pages
local routesFrame
local backToFarm, ovBtn
local routesLbl, rtScroll, rtChild
local impLbl, impBox, impBtn, crBtn
local createPage
local typeLabels = {}
local UI_Routes  = {}
local routeRows  = {}

-- ============================================================
-- EXPORT POPUP  (AceGUI Frame + MultiLineEditBox)
-- ============================================================
-- Store last route for Group share inside export frame
local _lastExportRoute = nil

function P.ShowExport(str, route)
    if not str or str=="" then P.prt("Nothing to export."); return end
    _lastExportRoute = route  -- store so Group button can use it
    local AceGUI = LibStub and LibStub("AceGUI-3.0", true)
    if not AceGUI then P.prt("Route: "..str); return end

    local frame = AceGUI:Create("Frame")
    frame:SetTitle("|cffCC2222RealNibba|r.Pack — Export Route")
    frame:SetStatusText("Ctrl+A, Ctrl+C to copy  |  or Share to Group below")
    frame:SetLayout("Flow")
    frame:SetWidth(500); frame:SetHeight(210)
    frame.frame:SetBackdropColor(0, 0, 0, 0)
    local _rtBg = frame.frame:CreateTexture(nil, "BACKGROUND")
    _rtBg:SetTexture("Interface\\AddOns\\RealNibba.Pack\\Images\\Backdrop")
    _rtBg:SetBlendMode("DISABLE"); _rtBg:SetAllPoints(frame.frame)

    -- Share to Group button (top of frame)
    local grpBtn = AceGUI:Create("Button")
    grpBtn:SetText("Share to Group")
    grpBtn:SetWidth(140)
    grpBtn:SetCallback("OnClick", function()
        if _lastExportRoute and P.ShareRouteToGroup then
            P:ShareRouteToGroup(_lastExportRoute)
        else
            P.prt("Join a group first to share!")
        end
    end)
    frame:AddChild(grpBtn)

    -- Spacer
    local sp = AceGUI:Create("Label"); sp:SetText(""); sp:SetWidth(350)
    frame:AddChild(sp)

    -- The editbox (no label - removes overlap)
    local editbox = AceGUI:Create("MultiLineEditBox")
    editbox:SetLabel("")  -- no label, no overlap
    editbox:SetText(str)
    editbox:SetFullWidth(true)
    editbox:SetHeight(130)
    editbox:DisableButton(true)
    frame:AddChild(editbox)

    frame:SetCallback("OnClose", function(widget) AceGUI:Release(widget) end)

    -- Auto-focus + select
    local eb = editbox.editBox
    if eb then
        local _t=0; local _f=CreateFrame("Frame")
        _f:SetScript("OnUpdate",function(self,e)
            _t=_t+e
            if _t>=0.1 then self:SetScript("OnUpdate",nil)
                eb:SetFocus(); eb:HighlightText() end
        end)
    end
end


-- ============================================================
-- ROUTES WINDOW  320 x 440
-- ── Title+div:          0  to  -24
-- ── [<Farming]|[Overlay]: -30  h=22  end=-52
-- ── DIV:                -58
-- ── Type checkboxes:    -65  h=20  end=-85
-- ── DIV:                -91
-- ── SAVED ROUTES label: -98  h=14  end=-112
-- ── Routes scroll:      -115  to  BOTTOMRIGHT+90
-- ── (bottom 90px reserved for import/create)
-- ── DIV:                -(440-90)=-350 → but let's use BOTTOMRIGHT
-- ── Import label:       -356  h=14  end=-370
-- ── Import box+btn:     -373  h=22  end=-395
-- ── Create Route btn:   -408  h=26  end=-434
-- ── bottom gap:         6px  ✓
-- ============================================================
routesFrame, _ = P.MakeWindow("RNPackRoutesFrame","RealNibba.Routes",WIN_W,WIN_H)
routesFrame:SetToplevel(true)
routesFrame:SetScript("OnMouseDown",function() routesFrame:Raise() end)
P.routesFrame = routesFrame
if P.RegisterScalableFrame then P.RegisterScalableFrame(routesFrame) end


-- ── [< Farming]  [Overlay: ON]  y=-30
backToFarm = P.MakeBtn("< Farming",routesFrame,80,BTN_H)
backToFarm:SetPoint("TOPLEFT",routesFrame,"TOPLEFT",BPAD,-30)
backToFarm:SetScript("OnClick",function()
    routesFrame:Hide(); if P.farmFrame then P.farmFrame:Show() end
end)

ovBtn = P.MakeBtn("Overlay: ON",routesFrame,90,BTN_H)
ovBtn:SetPoint("TOPRIGHT",routesFrame,"TOPRIGHT",-BPAD,-30)
ovBtn:SetScript("OnClick",function()
    local Ov=_RealNibbaOverlay
    if Ov then
        Ov.Options.ShowAll=not Ov.Options.ShowAll
        Ov.Modules.UpdateMap()
        ovBtn:SetText(Ov.Options.ShowAll and "Overlay: ON" or "Overlay: OFF")
    end
end)

-- ── DIV  y=-58

-- ── Type checkboxes  y=-65  h=20
local checkCount = 0
local typeX = BPAD
local function MakeTypeCheck(rtype, x)
    checkCount=checkCount+1
    local cb=CreateFrame("CheckButton","RNPackRTC"..checkCount,routesFrame,"UICheckButtonTemplate")
    cb:SetSize(24,24); cb:SetPoint("TOPLEFT",routesFrame,"TOPLEFT",x,-65)
    cb:SetChecked(true)
    local col=P.TYPE_COLOR[rtype]
    local lbl=routesFrame:CreateFontString(nil,"OVERLAY","GameFontNormalSmall")
    lbl:SetPoint("LEFT",cb,"RIGHT",2,0)
    lbl:SetTextColor(col.r,col.g,col.b,1); lbl:SetText(rtype)
    typeLabels[checkCount]=lbl
    local rt=rtype
    cb:SetScript("OnClick",function()
        if P.DB then
            P.DB.enabled[rt]=cb:GetChecked()==1 or cb:GetChecked()==true
            P.SyncToOverlay()
        end
    end)
    return x+86
end
typeX = MakeTypeCheck("Herbs", typeX)
typeX = MakeTypeCheck("Mines", typeX)
typeX = MakeTypeCheck("Mixed", typeX)

-- ── DIV  y=-91

-- ── SAVED ROUTES label  y=-98
routesLbl=routesFrame:CreateFontString(nil,"OVERLAY","GameFontNormalSmall")
routesLbl:SetPoint("TOPLEFT",routesFrame,"TOPLEFT",BPAD,-98)
routesLbl:SetTextColor(1,0.82,0,1); routesLbl:SetText("SAVED ROUTES")

-- ── Routes scroll  y=-115  BOTTOMRIGHT+90
rtScroll=CreateFrame("ScrollFrame","RNPackRtScroll",routesFrame,"UIPanelScrollFrameTemplate")
rtScroll:SetPoint("TOPLEFT",  routesFrame,"TOPLEFT",  BPAD,    -115)
rtScroll:SetPoint("BOTTOMRIGHT",routesFrame,"BOTTOMRIGHT",-BPAD-18, 90)
rtChild=CreateFrame("Frame",nil,rtScroll)
rtChild:SetSize(rtScroll:GetWidth() or 260,1); rtScroll:SetScrollChild(rtChild)

-- ── Bottom section (90px from bottom)
-- ── DIV  at -(440-90+6) = -356? Use fixed positions from top:
local btmBase = WIN_H - 90  -- = 350px from top

-- Divider at top of bottom section
local btmDiv = nil  -- divider removed

-- ── Import label  y=-(btmBase+7)
impLbl=routesFrame:CreateFontString(nil,"OVERLAY","GameFontNormalSmall")
impLbl:SetPoint("TOPLEFT",routesFrame,"TOPLEFT",BPAD,-(btmBase+7))
impLbl:SetTextColor(0.8,0.8,0.8,1); impLbl:SetText("Import Route:")

-- ── Import box + button  y=-(btmBase+7+LBL_H+GAP_S)=-(350+7+14+3)=-374
local impY = -(btmBase + 7 + LBL_H + GAP_S)
impBox=CreateFrame("EditBox","RNPackImportBox",routesFrame,"InputBoxTemplate")
impBox:SetSize(WIN_W - BPAD*2 - 68, 20)
impBox:SetPoint("TOPLEFT",routesFrame,"TOPLEFT",BPAD,impY)
impBox:SetAutoFocus(false); impBox:SetMaxLetters(0)
impBox:SetScript("OnEscapePressed",function() impBox:ClearFocus() end)

impBtn=P.MakeBtn("Import",routesFrame,60,20)
impBtn:SetPoint("LEFT",impBox,"RIGHT",GAP_S,0)
impBtn:SetScript("OnClick",function()
    local str=impBox:GetText()
    local route,err=P.ImportString(str)
    if not route then P.prt("Import failed: "..(err or "?")); return end
    P.DB.routes[route.name]=route
    P.SyncToOverlay(); UI_Routes.RefreshList()
    impBox:SetText(""); P.prt("Imported: "..route.name)
end)

-- ── Create Route button  y=impY-22-GAP
local crY = impY - 22 - GAP
crBtn=P.MakeBtn("+ Create New Route",routesFrame,WIN_W-BPAD*2,26)
crBtn:SetPoint("TOPLEFT",routesFrame,"TOPLEFT",BPAD,crY)

-- ============================================================
-- CREATE ROUTE SUB-PAGE
-- ============================================================
createPage=CreateFrame("Frame",nil,routesFrame)
createPage:SetPoint("TOPLEFT",routesFrame,"TOPLEFT",BPAD,-30)
createPage:SetPoint("BOTTOMRIGHT",routesFrame,"BOTTOMRIGHT",-BPAD,BPAD)
createPage:Hide()

local function ShowCreatePage()
    createPage:Show()
    backToFarm:Hide(); ovBtn:Hide()
    if btmDiv then btmDiv:Hide() end
    crBtn:Hide(); impBox:Hide(); impBtn:Hide(); impLbl:Hide()
    rtScroll:Hide(); routesLbl:Hide()
    for i=1,9 do
        local f=_G["RNPackRTC"..i]; if f then f:Hide() end
        if typeLabels[i] then typeLabels[i]:Hide() end
    end
end
local function HideCreatePage()
    createPage:Hide()
    backToFarm:Show(); ovBtn:Show()
    if btmDiv then btmDiv:Show() end
    crBtn:Show(); impBox:Show(); impBtn:Show(); impLbl:Show()
    rtScroll:Show(); routesLbl:Show()
    for i=1,9 do
        local f=_G["RNPackRTC"..i]; if f then f:Show() end
        if typeLabels[i] then typeLabels[i]:Show() end
    end
    UI_Routes.RefreshList()
end

-- Create page content (all Y relative to createPage top = routesFrame y=-30)
local cpW = WIN_W - BPAD*2

-- [< Routes] button + title  y=0 (top of createPage)
local crBack=P.MakeBtn("< Routes",createPage,70,BTN_H)
crBack:SetPoint("TOPLEFT",createPage,"TOPLEFT",0,0)
crBack:SetScript("OnClick",function()
    if P.rec.active then P.rec.active=false; P.WP.Hide() end
    HideCreatePage()
end)
local crTitle=createPage:CreateFontString(nil,"OVERLAY","GameFontNormal")
crTitle:SetPoint("LEFT",crBack,"RIGHT",GAP,0)
crTitle:SetTextColor(1,0.82,0,1); crTitle:SetText("Create New Route")

-- Name  y=-30
local y = -30
createPage:CreateFontString(nil,"OVERLAY","GameFontNormalSmall"):SetPoint("TOPLEFT",createPage,"TOPLEFT",0,y)
createPage:GetChildren()  -- just for the lbl below

local nameLbl=createPage:CreateFontString(nil,"OVERLAY","GameFontNormalSmall")
nameLbl:SetPoint("TOPLEFT",createPage,"TOPLEFT",0,y)
nameLbl:SetTextColor(0.8,0.8,0.8,1); nameLbl:SetText("Route Name:")
y = y - LBL_H - GAP_S

local nameInput=CreateFrame("EditBox","RNPackRouteNameInput",createPage,"InputBoxTemplate")
nameInput:SetSize(cpW,20); nameInput:SetPoint("TOPLEFT",createPage,"TOPLEFT",0,y)
nameInput:SetAutoFocus(false); nameInput:SetMaxLetters(12); nameInput:SetText("My Route")
nameInput:SetScript("OnEditFocusGained",function()
    if nameInput:GetText()=="My Route" then nameInput:SetText("") end end)
nameInput:SetScript("OnEditFocusLost",function()
    if nameInput:GetText()=="" then nameInput:SetText("My Route") end end)
P.recNameInput=nameInput
y = y - 20 - GAP

-- Type  y
local typeLbl=createPage:CreateFontString(nil,"OVERLAY","GameFontNormalSmall")
typeLbl:SetPoint("TOPLEFT",createPage,"TOPLEFT",0,y)
typeLbl:SetTextColor(0.8,0.8,0.8,1); typeLbl:SetText("Route Type:")
y = y - LBL_H - GAP_S

-- Route type selector using EasyMenu (native WoW API, always works)
local typeOpts = {"Herbs","Mines","Mixed"}; local typeIdx = 1

-- Forward-declare typeBtn so the EasyMenu func closure can reference it
local typeBtn

-- Shared hidden frame required by EasyMenu API
local typeMenuAnchor = CreateFrame("Frame","RNPackTypeMenuAnchor",UIParent,"UIDropDownMenuTemplate")

local function OpenTypeMenu()
    local menuList = {
        {text="Route Type", isTitle=true, notCheckable=true},
    }
    local typeColors = {
        Herbs = {0.10,0.85,0.10},
        Mines = {0.10,0.40,1.00},
        Mixed = {1.00,0.55,0.00},
    }
    for i, opt in ipairs(typeOpts) do
        local oi = i
        local col = typeColors[opt] or {1,1,1}
        local hexCol = string.format("|cff%02x%02x%02x",
            math.floor(col[1]*255), math.floor(col[2]*255), math.floor(col[3]*255))
        menuList[#menuList+1] = {
            text        = hexCol..opt.."|r",
            notCheckable= false,
            checked     = (typeIdx == i),
            func        = function()
                typeIdx = oi
                if typeBtn then typeBtn:SetText(typeOpts[oi].." ▾") end
            end,
        }
    end
    EasyMenu(menuList, typeMenuAnchor, "cursor", 0, 0, "MENU", 1)
end

-- Assign typeBtn (no 'local' - reuses the forward declaration above)
typeBtn = P.MakeBtn(typeOpts[1].." ▾", createPage, 110, BTN_H)
typeBtn:SetPoint("TOPLEFT",createPage,"TOPLEFT",0,y)
typeBtn:SetScript("OnClick", function() OpenTypeMenu() end)
y = y - BTN_H - GAP

-- Thickness
local thickLbl=createPage:CreateFontString(nil,"OVERLAY","GameFontNormalSmall")
thickLbl:SetPoint("TOPLEFT",createPage,"TOPLEFT",0,y)
thickLbl:SetTextColor(0.8,0.8,0.8,1); thickLbl:SetText("Line Thickness:")
y = y - LBL_H - GAP_S

-- Thickness: 3 checkboxes (Thin / Medium / Thick)
local curThick  = 3
local thickCBs  = {}
local thickNames = {"Thin","Medium","Thick"}
local thickCols  = {{0.7,0.7,0.7},{0.2,0.9,0.2},{0.2,0.7,1.0}}
local cbW        = math.floor(cpW/3)

local function SetThickCB(sel)
    curThick = sel
    if P.RIBBON_LEVELS then RIBBON = P.RIBBON_LEVELS[sel] end
    for j,cb in ipairs(thickCBs) do cb:SetChecked(j==sel) end
end

for i=1,3 do
    local cb=CreateFrame("CheckButton",nil,createPage,"UICheckButtonTemplate")
    cb:SetSize(24,24)
    cb:SetPoint("TOPLEFT",createPage,"TOPLEFT",(i-1)*cbW,y)
    local c=thickCols[i]
    local lbl=createPage:CreateFontString(nil,"OVERLAY","GameFontNormal")
    lbl:SetPoint("LEFT",cb,"RIGHT",4,0)
    lbl:SetText(thickNames[i]); lbl:SetTextColor(c[1],c[2],c[3],1)
    local li=i
    cb:SetScript("OnClick",function() SetThickCB(li) end)
    thickCBs[i]=cb
end
SetThickCB(3)          -- default: Thick
y = y - 26 - GAP

-- Status box
local statusBox=CreateFrame("Frame",nil,createPage)
statusBox:SetSize(cpW,40); statusBox:SetPoint("TOPLEFT",createPage,"TOPLEFT",0,y)
statusBox:SetBackdrop(P.BACKDROP_DARK)
statusBox:SetBackdropColor(0.05,0.05,0.05,0.9)
statusBox:SetBackdropBorderColor(0.4,0.35,0.25,0.8)
local statusLbl=statusBox:CreateFontString(nil,"OVERLAY","GameFontNormalSmall")
statusLbl:SetPoint("CENTER",statusBox,"CENTER",0,0)
statusLbl:SetText("Ready to record."); statusLbl:SetTextColor(0.9,0.9,0.9,1)
P.recStatusLbl=statusLbl
y = y - 40 - GAP

-- Start/Stop record buttons
local recBW=math.floor((cpW-GAP_S)/2)
local startRecBtn=P.MakeBtn("Start Recording",createPage,recBW,BTN_H)
startRecBtn:SetPoint("TOPLEFT",createPage,"TOPLEFT",0,y)
local stopRecBtn=P.MakeBtn("Stop Recording",createPage,recBW,BTN_H)
stopRecBtn:SetPoint("LEFT",startRecBtn,"RIGHT",GAP_S,0)
y = y - BTN_H - GAP

-- Send section (hidden until recording stops)
local sendLbl=createPage:CreateFontString(nil,"OVERLAY","GameFontNormalSmall")
sendLbl:SetPoint("TOPLEFT",createPage,"TOPLEFT",0,y)
sendLbl:SetTextColor(0.7,0.7,0.7,1); sendLbl:SetText("Send to Overlay?"); sendLbl:Hide()
y = y - LBL_H - GAP_S

local sendBtn=P.MakeBtn("SEND TO OVERLAY",createPage,cpW,BTN_H+4)
sendBtn:SetPoint("TOPLEFT",createPage,"TOPLEFT",0,y); sendBtn:Hide()

local lastRoute=nil

startRecBtn:SetScript("OnClick",function()
    local name=nameInput:GetText()
    if name=="" or name=="My Route" then P.prt("Enter a route name!"); return end
    P.StartRecording(name,typeOpts[typeIdx])
    statusLbl:SetText("|cff00FF44Recording...|r  0 pts")
    startRecBtn:SetText("Recording...")
    startRecBtn:GetNormalTexture():SetVertexColor(0.25,0.60,0.25)
    sendLbl:Hide(); sendBtn:Hide(); lastRoute=nil
    -- Lock UI during recording
    nameInput:ClearFocus()
    nameInput:EnableKeyboard(false)
    for _,cb in ipairs(thickCBs) do cb:Disable() end
    P.prt("Recording: |cffffff00"..name.."|r ("..typeOpts[typeIdx]..")")
end)

stopRecBtn:SetScript("OnClick",function()
    if not P.rec.active then P.prt("Not recording."); return end
    local route,err=P.StopRecording(curThick)
    if not route then P.prt("Error: "..(err or "?")); return end
    lastRoute=route
    statusLbl:SetText(string.format("|cffffff00%s|r  %d pts  %d tris",
        route.name,#P.rec.pts,route.tris))
    startRecBtn:SetText("Start Recording")
    startRecBtn:GetNormalTexture():SetVertexColor(1,1,1)
    -- Unlock UI
    nameInput:EnableKeyboard(true)
    for _,cb in ipairs(thickCBs) do cb:Enable() end
    sendLbl:Show(); sendBtn:Show()
    P.DB.routes[route.name]=route
    P.prt("Recorded: |cffffff00"..route.name.."|r  "..route.tris.." tris")
end)

sendBtn:SetScript("OnClick",function()
    if not lastRoute then return end
    if P.SyncToOverlay() then
        local Ov=_RealNibbaOverlay
        if Ov then
            if Ov.Modules and Ov.Modules.UpdateMap then Ov.Modules.UpdateMap() end
            if Ov.Synchronize then Ov.Synchronize(RealNibbaOverlayOptions) end
        end
        P.prt("|cff00FF44Sent!|r  "..lastRoute.name.." is on your map.")
    else P.prt("Overlay not loaded — saved to DB.") end
    HideCreatePage()
end)

crBtn:SetScript("OnClick",function()
    ShowCreatePage()
    statusLbl:SetText("Ready to record.")
    startRecBtn:SetText("Start Recording")
    startRecBtn:GetNormalTexture():SetVertexColor(1,1,1)
    sendLbl:Hide(); sendBtn:Hide(); lastRoute=nil
end)

-- ============================================================
-- ROUTES LIST
-- ============================================================
function UI_Routes.RefreshList()
    for _,r in ipairs(routeRows) do r:Hide() end; routeRows={}
    if not P.DB then return end
    local rowH=26; local y=0; local W=rtChild:GetWidth() or 260
    for name,route in pairs(P.DB.routes) do
        local row=CreateFrame("Frame",nil,rtChild)
        row:SetHeight(rowH); row:SetPoint("TOPLEFT",rtChild,"TOPLEFT",0,y)
        row:SetPoint("TOPRIGHT",rtChild,"TOPRIGHT",0,y)
        local rbg=row:CreateTexture(nil,"BACKGROUND"); rbg:SetAllPoints()
        rbg:SetTexture(0.12,0.12,0.14,0.5)
        -- Name: max 12 chars, colored by type
        local col = P.TYPE_COLOR[route.rtype] or {r=1,g=1,b=1}
        local dispName = name
        if #dispName > 12 then dispName = string.sub(dispName,1,12) end
        local nl=row:CreateFontString(nil,"OVERLAY","GameFontNormalSmall")
        nl:SetPoint("LEFT",row,"LEFT",3,0); nl:SetWidth(90)
        nl:SetJustifyH("LEFT"); nl:SetText(dispName)
        nl:SetTextColor(col.r,col.g,col.b,1)
        -- Zone in middle; fall back to overlay zone name for old routes without zone saved
        local Ov = _RealNibbaOverlay
        local dispZone = route.zone or (Ov and Ov.GetZoneName and Ov.GetZoneName(route.mapID)) or ""
        if #dispZone > 16 then dispZone = string.sub(dispZone,1,16) end
        local zoneLbl=row:CreateFontString(nil,"OVERLAY","GameFontNormalSmall")
        zoneLbl:SetPoint("LEFT",row,"LEFT",96,0); zoneLbl:SetWidth(W-166)
        zoneLbl:SetJustifyH("LEFT"); zoneLbl:SetText(dispZone)
        zoneLbl:SetTextColor(0.55,0.55,0.55,1)
        -- [X] rightmost, [Export] 2px to its left
        local delBtn=P.MakeBtn("X",row,20,20)
        delBtn:SetPoint("RIGHT",row,"RIGHT",-2,0)
        local shareBtn=P.MakeBtn("Export",row,50,20)
        shareBtn:SetPoint("RIGHT",delBtn,"LEFT",-2,0)
        local r2=route
        shareBtn:SetScript("OnClick",function()
            local str=P.ExportString(r2)
            if str then P.ShowExport(str,r2)
            else P.prt("Re-record to enable sharing.") end
        end)
        local rn=name
        delBtn:SetScript("OnClick",function()
            P.DB.routes[rn]=nil; P.SyncToOverlay(); UI_Routes.RefreshList()
        end)
        routeRows[#routeRows+1]=row; row:Show()
        if _G.RNPackSkinFrame then _G.RNPackSkinFrame(row) end
        y=y-rowH-GAP_S
    end
    rtChild:SetHeight(math.max(1,math.abs(y)))
    if #routeRows==0 then
        local el=routesFrame:CreateFontString(nil,"OVERLAY","GameFontNormalSmall")
        el:SetPoint("TOPLEFT",rtChild,"TOPLEFT",4,-4)
        el:SetTextColor(0.5,0.5,0.5,1); el:SetText("No routes saved.")
        routeRows[1]=el
    end
end

P.UI_Routes = UI_Routes
routesFrame:Hide()
