local GSE = GSE

local Statics = GSE.Static

local L = GSE.L
local function DisablePreviewColoring(widget)
    if widget and widget.editBox and IndentationLib and IndentationLib.disable then
        IndentationLib.disable(widget.editBox)
    end
end

function GSE.GUIShowCompiledMacroGui(spelllist, title, editframe)
  local AceGUI = LibStub("AceGUI-3.0")

  -- Reuse an existing preview frame for this editor rather than leaking a new
  -- one on every button click.
  local PreviewFrame = editframe.PreviewFrame
  if GSE.isEmpty(PreviewFrame) then
    PreviewFrame = AceGUI:Create("Frame")
    PreviewFrame.frame:SetFrameStrata("MEDIUM")
    PreviewFrame.frame:SetClampedToScreen(true)
    PreviewFrame:SetTitle(L["Compiled Template"])
    PreviewFrame:SetCallback(
      "OnClose",
      function(widget)
        PreviewFrame:Hide()
        -- Editor's macro blocks render the inline side panel only when this
        -- preview frame is visible, so a refresh is needed on close to drop
        -- the panel and let the multiline take full width again.
        if editframe and editframe.RefreshCurrentVersion then
          editframe.RefreshCurrentVersion()
        end
      end
    )
    PreviewFrame:SetLayout("List")
    PreviewFrame.frame:SetClampRectInsets(-10, -10, -10, -10)
    PreviewFrame:SetWidth(280)
    PreviewFrame:SetHeight(700)
    PreviewFrame:Hide()

    local PreviewLabel = AceGUI:Create("MultiLineEditBox")
    PreviewLabel:SetWidth(270)
    PreviewLabel:SetNumLines(40)
    PreviewLabel:DisableButton(true)

    PreviewFrame.PreviewLabel = PreviewLabel
    PreviewFrame:AddChild(PreviewLabel)

    IndentationLib.enable(PreviewLabel.editBox, Statics.IndentationColorTable, 4)
    PreviewLabel:SetCallback("OnRelease", DisablePreviewColoring)

    PreviewFrame.frame:SetScript(
      "OnSizeChanged",
      function(self, width, height)
        PreviewLabel:SetWidth(width - 30)
        PreviewLabel:SetHeight(height - 80)
      end
    )

    -- Store on the editor so OnClose can dismiss it and repeat clicks reuse it.
    editframe.PreviewFrame = PreviewFrame
  end

  local PreviewLabel = PreviewFrame.PreviewLabel
  PreviewFrame.text = IndentationLib.encode(GSE.Dump(spelllist))

  local count = #spelllist
  PreviewLabel:SetLabel(L["Compiled"] .. " " .. count .. " " .. L["Actions"])
  if editframe:IsVisible() then
    PreviewFrame:ClearAllPoints()
    PreviewFrame:SetPoint("TOPLEFT", editframe.frame, editframe.Width + 10, 0)
  end

  if not GSE.isEmpty(spelllist) then
    PreviewLabel:SetText(PreviewFrame.text)
  end
  PreviewFrame:SetStatusText(title)
  local wasShown = PreviewFrame:IsShown()
  PreviewFrame:Show()
  -- Refresh editor macro blocks so the inline side panel appears alongside
  -- the multiline editor whenever this preview frame becomes visible.
  if not wasShown and editframe and editframe.RefreshCurrentVersion then
    editframe.RefreshCurrentVersion()
  end
end
