local ADDON_NAME, RPAL = ...

-- ============================================================
-- RPAL SESSION QUICK WIDGET
-- Small, theme-aware, draggable play/stop control for Sessions.
-- Left click toggles the active Session. Right-button drag moves it.
-- ============================================================

local WIDGET_W, WIDGET_H = 150, 42
local FONT = STANDARD_TEXT_FONT or "Fonts\\FRIZQT__.TTF"
local WHITE = "Interface\\Buttons\\WHITE8X8"

local function Palette()
    if RPAL.GetCurrentThemePalette then
        local p=RPAL.GetCurrentThemePalette()
        if p then return p end
    end
    return {
        main={.075,.042,.022,.99},panel={.105,.065,.035,.98},panel2={.16,.105,.055,.98},
        border={.42,.28,.12,1},button={.105,.070,.040,1},buttonHover={.17,.115,.060,1},
        gold={.86,.63,.28,1},pale={.88,.82,.68,1},muted={.57,.50,.40,1},green={.40,.88,.58,1}
    }
end

local function Scaled(n)
    return RPAL.GetScaledFontSize and RPAL.GetScaledFontSize(n) or n
end

local function ApplyBackdrop(f,bg,border)
    f:SetBackdrop({
        bgFile="Interface\\Tooltips\\UI-Tooltip-Background",
        edgeFile="Interface\\Tooltips\\UI-Tooltip-Border",
        tile=false,tileSize=16,edgeSize=16,
        insets={left=4,right=4,top=4,bottom=4}
    })
    f:SetBackdropColor(bg[1],bg[2],bg[3],bg[4] or 1)
    f:SetBackdropBorderColor(border[1],border[2],border[3],border[4] or 1)
end

local function EnsureDB()
    if type(RPAL_DB)~="table" then RPAL_DB={} end
    RPAL_DB.settings=RPAL_DB.settings or {}
    RPAL_DB.settings.sessionWidget=RPAL_DB.settings.sessionWidget or {}
    local s=RPAL_DB.settings.sessionWidget
    if s.point==nil then s.point="CENTER" end
    if s.x==nil then s.x=0 end
    if s.y==nil then s.y=-250 end
    local settings=RPAL.GetSettings and RPAL.GetSettings() or RPAL_DB.settings
    -- Visibility now has one account setting. Ignore the legacy nested default
    -- (which used to turn itself on automatically) so this widget starts hidden
    -- until the player explicitly enables it in Settings.
    s.enabled=settings.sessionWidgetEnabled and true or false
    return s
end

local function SavePosition(f)
    local s=EnsureDB()
    local point,_,_,x,y=f:GetPoint(1)
    s.point=point or "CENTER"
    s.x=x or 0
    s.y=y or 0
end

local function Tooltip(title,body)
    if RPAL.ShowSimpleCursorTooltip then
        RPAL.ShowSimpleCursorTooltip(title,body,Palette().gold,"SESSIONS")
    end
end

local function HideTooltip()
    if RPAL.HideCursorTooltip then RPAL.HideCursorTooltip() end
end

local function SetIcon(tex,path,c)
    if not tex then return end
    tex:SetTexture(path)
    tex:SetTexCoord(.06,.94,.06,.94)
    if c then tex:SetVertexColor(c[1],c[2],c[3],c[4] or 1) else tex:SetVertexColor(1,1,1,1) end
end

local function Refresh(f)
    if not f then return end
    local p=Palette()
    local active=RPAL.IsSceneActive and RPAL.IsSceneActive() or false
    local stored=RPAL.GetStoredSceneCount and RPAL.GetStoredSceneCount() or 0
    local accent=active and p.green or p.gold
    f.label:SetText(active and "STOP SESSION" or "START SESSION")
    f.label:SetTextColor(accent[1],accent[2],accent[3],accent[4] or 1)
    f.sub:SetText(active and "Session in progress" or (stored>0 and (tostring(stored).." paused Session"..(stored==1 and "" or "s")) or "Quick Session"))
    f.sub:SetTextColor(p.muted[1],p.muted[2],p.muted[3],p.muted[4] or 1)
    SetIcon(f.icon,RPAL.ICONS and (active and RPAL.ICONS.pause or RPAL.ICONS.play),accent)
    ApplyBackdrop(f,active and p.panel2 or p.panel,p.border)
    if f.glow then
        f.glow:SetColorTexture(accent[1],accent[2],accent[3],active and .13 or .07)
    end
end

function RPAL.UpdateSessionWidget()
    if RPAL._sessionWidget then Refresh(RPAL._sessionWidget) end
end

function RPAL.ResetSessionWidget()
    local f=RPAL._sessionWidget
    if not f then return end
    f:Hide()
    f:SetScript("OnUpdate",nil)
    f:ClearAllPoints()
    local s=EnsureDB()
    f:SetPoint(s.point or "CENTER",UIParent,s.point or "CENTER",tonumber(s.x) or 0,tonumber(s.y) or -250)
    Refresh(f)
    if s.enabled then f:Show() end
end

function RPAL.CreateSessionWidget()
    if RPAL._sessionWidget then
        Refresh(RPAL._sessionWidget)
        return RPAL._sessionWidget
    end
    local s=EnsureDB()
    local f=CreateFrame("Button","RPALSessionQuickWidget",UIParent,"BackdropTemplate")
    RPAL._sessionWidget=f
    f:SetSize(WIDGET_W,WIDGET_H)
    f:SetFrameStrata("MEDIUM")
    f:SetFrameLevel(60)
    f:SetClampedToScreen(true)
    f:SetMovable(true)
    f:RegisterForClicks("LeftButtonUp","RightButtonDown","RightButtonUp")
    f:RegisterForDrag("RightButton")
    f:EnableMouse(true)
    f:SetPoint(s.point or "CENTER",UIParent,s.point or "CENTER",tonumber(s.x) or 0,tonumber(s.y) or -250)

    local glow=f:CreateTexture(nil,"BACKGROUND",nil,-1)
    f.glow=glow
    glow:SetPoint("TOPLEFT",2,-2);glow:SetPoint("BOTTOMRIGHT",-2,2)
    glow:SetTexture(WHITE)

    local icon= f:CreateTexture(nil,"ARTWORK")
    f.icon=icon
    icon:SetSize(23,23)
    icon:SetPoint("LEFT",10,1)

    local label=f:CreateFontString(nil,"OVERLAY")
    f.label=label
    label:SetFont(FONT,Scaled(11),"")
    if RPAL.RegisterScalableFontObject then RPAL.RegisterScalableFontObject(label,FONT,11,"") end
    label:SetPoint("TOPLEFT",42,-8)
    label:SetPoint("RIGHT",-8,0)
    label:SetJustifyH("LEFT")
    label:SetShadowColor(0,0,0,.92);label:SetShadowOffset(1,-1)

    local sub=f:CreateFontString(nil,"OVERLAY")
    f.sub=sub
    sub:SetFont(FONT,Scaled(8),"")
    if RPAL.RegisterScalableFontObject then RPAL.RegisterScalableFontObject(sub,FONT,8,"") end
    sub:SetPoint("BOTTOMLEFT",42,7)
    sub:SetPoint("RIGHT",-8,0)
    sub:SetJustifyH("LEFT")
    sub:SetShadowColor(0,0,0,.92);sub:SetShadowOffset(1,-1)

    f:SetScript("OnClick",function(self,button)
        if button~="LeftButton" then return end
        if RPAL.IsSceneActive and RPAL.IsSceneActive() then
            if RPAL.RequestEndScene then RPAL.RequestEndScene() end
        else
            if RPAL.StartScene then
                local ok,err=RPAL.StartScene()
                if not ok and err then
                    if RPAL.ShowSessionStatusToast then RPAL.ShowSessionStatusToast(tostring(err),"PAUSED")
                    else print("|cffff7777ODYN:|r "..tostring(err)) end
                end
            end
        end
        Refresh(self)
        if RPAL.RefreshSceneButtons then RPAL.RefreshSceneButtons() end
        if RPAL.RefreshBookChrome then RPAL.RefreshBookChrome() end
    end)

    f:SetScript("OnDragStart",function(self,button)
        if button=="RightButton" then
            self._dragging=true
            self:StartMoving()
        end
    end)
    f:SetScript("OnDragStop",function(self,button)
        if self._dragging then
            self:StopMovingOrSizing()
            self._dragging=false
            SavePosition(self)
        end
    end)
    f:SetScript("OnEnter",function(self)
        local active=RPAL.IsSceneActive and RPAL.IsSceneActive() or false
        Tooltip(active and "Session Options" or "Start Session",active and "Pause & Store for later, or End & Record now. Right-drag to move this widget." or "Start a Session immediately. Paused Sessions can be resumed from Sessions. Right-drag to move this widget.")
    end)
    f:SetScript("OnLeave",HideTooltip)

    Refresh(f)
    if s.enabled then f:Show() else f:Hide() end
    return f
end

function RPAL.SetSessionWidgetShown(show)
    local f=RPAL.CreateSessionWidget()
    local enabled=show and true or false
    local settings=RPAL.GetSettings and RPAL.GetSettings() or (RPAL_DB and RPAL_DB.settings)
    if settings then settings.sessionWidgetEnabled=enabled end
    EnsureDB().enabled=enabled
    if show then f:Show() else f:Hide() end
end
