local API = rawget(_G, "LIDCOUNCIL_API")
local INTERNAL_API = type(API) == "table" and type(API.__internal) == "table" and API.__internal or nil
if type(INTERNAL_API) ~= "table" then
  error("LidCouncil missing internal API registry.")
end

local function CreateAboutFAQSection(editor, aboutContent, deps)
  deps = deps or {}
  local MakeAboutTitle = deps.MakeAboutTitle
  local SafeHookScript = deps.SafeHookScript or function(frame, scriptName, handler)
    if frame and type(frame.HookScript) == "function" and type(handler) == "function" then
      pcall(frame.HookScript, frame, scriptName, handler)
    end
  end
  local GetTitleColor = type(deps.GetTitleColor) == "function" and deps.GetTitleColor or function()
    return 0.6588, 0.4784, 0.9098, 1.0
  end
  local function ApplyTitleColor(fontString)
    if not fontString then
      return
    end
    local r, g, b, a = GetTitleColor()
    fontString:SetTextColor(r, g, b, a)
  end

  local aboutFAQFrame = CreateFrame("Frame", nil, aboutContent)
  aboutFAQFrame:SetAllPoints(aboutContent)
  aboutFAQFrame:Hide()
  editor.aboutFAQFrame = aboutFAQFrame

  local faqHeader = CreateFrame("Frame", nil, aboutFAQFrame)
  faqHeader:SetPoint("TOPLEFT", 0, 0)
  faqHeader:SetPoint("TOPRIGHT", 0, 0)
  faqHeader:SetHeight(44)

  local faqTitle = MakeAboutTitle(aboutFAQFrame, "FAQ", 0, 0)
  editor.aboutFaqTitle = faqTitle

  local faqSearchLabel = aboutFAQFrame:CreateFontString(nil, "OVERLAY", "GameFontHighlightSmall")
  faqSearchLabel:SetPoint("TOPLEFT", faqHeader, "TOPLEFT", 0, -22)
  faqSearchLabel:SetText("Search:")
  editor.aboutFaqSearchLabel = faqSearchLabel

  local faqSearchBox = CreateFrame("EditBox", nil, aboutFAQFrame, "InputBoxTemplate")
  faqSearchBox:SetSize(260, 20)
  faqSearchBox:SetPoint("LEFT", faqSearchLabel, "RIGHT", 6, 0)
  faqSearchBox:SetAutoFocus(false)
  faqSearchBox:SetText("")

  local faqContainer = CreateFrame("Frame", nil, aboutFAQFrame)
  faqContainer:SetPoint("TOPLEFT", faqHeader, "BOTTOMLEFT", 0, -8)
  faqContainer:SetPoint("TOPRIGHT", faqHeader, "BOTTOMRIGHT", -10, -8)
  faqContainer:SetHeight(10)
  editor.aboutFAQContainer = faqContainer

  local FAQ_ENTRIES = {
    {
      section = "LidCouncil",
      q = "How does LidCouncil affect my FPS?",
      a = [[- tbv
- tbv
- tbv]]
    },
    {
      section = "LidCouncil",
      q = "How many Profiles can I create?",
      a = [[- There is no hard limit.
- Profiles are stored in SavedVariables; practical limits depend on memory and disk size.]]
    },
    {
      section = "Loot Rules",
      q = "In World of Warcraft Midnight, if I run a dungeon everything is personal loot and higher item level upgrades usually cannot be traded. In raids I believe it is different and I can still trade items that I win. Is that correct?",
      a = [[- Yes. Your understanding is basically correct.
- In Midnight dungeons and Mythic+, loot is still effectively personal loot, so the normal personal-loot trade restrictions apply. If the item is a higher item level than what your character already has for that slot, you generally cannot trade it even if you do not want it.
- In Normal, Heroic, and Mythic raids it is different because raids use Group Loot instead of personal loot. If you win an item through the raid roll system, it is generally tradeable to eligible players in the raid even if it is an item-level upgrade for you.
- One caveat: LFR can behave differently from organized Normal, Heroic, and Mythic raiding. When people talk about freely tradeable raid loot, they usually mean the organized raid Group Loot modes, not every LFR edge case.]]
    },
    {
      section = "AUTO-PASS",
      q = "Will the AUTO-PASS pass on every item?",
      a = [[- Only on gear which is tradeable in raid.
- Toys, Collectibles, Heartstones, Housing Decor, and similar personal items are not part of the AUTO-PASS flow and the raid will use the Blizzard rolls for these items.
- The reason is that some items in these categories are tradeable while others are not, so LidCouncil leaves them personal and only keeps them visible as Non-Council Items.]]
    },
  }

  local faqLines = {}
  local faqDividers = {}

  local function GetLine(index)
    local fs = faqLines[index]
    if not fs then
      fs = faqContainer:CreateFontString(nil, "OVERLAY", "GameFontHighlightSmall")
      fs:SetJustifyH("LEFT")
      faqLines[index] = fs
    end
    return fs
  end

  local function HideUnused(fromIndex)
    for i = fromIndex, #faqLines do
      faqLines[i]:Hide()
    end
  end

  local function GetFAQDivider(index)
    local tx = faqDividers[index]
    if not tx then
      tx = faqContainer:CreateTexture(nil, "ARTWORK")
      tx:SetColorTexture(1, 1, 1, 0.14)
      tx:SetHeight(1)
      faqDividers[index] = tx
    end
    return tx
  end

  local function HideUnusedDividers(fromIndex)
    for i = fromIndex, #faqDividers do
      faqDividers[i]:Hide()
    end
  end

  local function UpdateFAQText()
    local term = string.lower(faqSearchBox:GetText() or "")
    local width = (aboutContent:GetWidth() or 560) - 14
    if width < 200 then width = 200 end

    local lineIndex = 1
    local dividerIndex = 1
    local y = 0
    local any = false
    local lastSection = nil

    for _, entry in ipairs(FAQ_ENTRIES) do
      local section = entry.section or ""
      local q = entry.q or ""
      local a = entry.a or ""
      local hay = string.lower(section .. " " .. q .. " " .. a)

      if term == "" or hay:find(term, 1, true) then
        any = true

        if section ~= "" and section ~= lastSection then
          local sectionDivider = GetFAQDivider(dividerIndex); dividerIndex = dividerIndex + 1
          sectionDivider:ClearAllPoints()
          sectionDivider:SetPoint("TOPLEFT", faqContainer, "TOPLEFT", 0, y)
          sectionDivider:SetWidth(width)
          sectionDivider:Show()
          y = y - 12

          local secLine = GetLine(lineIndex); lineIndex = lineIndex + 1
          secLine:ClearAllPoints()
          secLine:SetPoint("TOPLEFT", faqContainer, "TOPLEFT", 0, y)
          secLine:SetWidth(width)
          secLine:SetText(section)
          local secFont, _, secFlags = secLine:GetFont()
          secLine:SetFont(secFont, 16, secFlags)
          ApplyTitleColor(secLine)
          secLine:Show()
          y = y - (secLine:GetStringHeight() + 8)
          lastSection = section
        end

        local qLine = GetLine(lineIndex); lineIndex = lineIndex + 1
        qLine:ClearAllPoints()
        qLine:SetPoint("TOPLEFT", faqContainer, "TOPLEFT", 0, y)
        qLine:SetWidth(width)
        qLine:SetText(q)
        local qFont, _, qFlags = qLine:GetFont()
        qLine:SetFont(qFont, 13, qFlags)
        ApplyTitleColor(qLine)
        qLine:Show()
        y = y - (qLine:GetStringHeight() + 4)

        local aLine = GetLine(lineIndex); lineIndex = lineIndex + 1
        aLine:ClearAllPoints()
        aLine:SetPoint("TOPLEFT", faqContainer, "TOPLEFT", 0, y)
        aLine:SetWidth(width)
        local bullet = string.char(226, 128, 162)
        local renderedAnswer = tostring(a or "")
        renderedAnswer = renderedAnswer:gsub("^%-%s", bullet .. " ")
        renderedAnswer = renderedAnswer:gsub("\n%-%s", "\n" .. bullet .. " ")
        aLine:SetText(renderedAnswer)
        local aFont, _, aFlags = aLine:GetFont()
        aLine:SetFont(aFont, 13, aFlags)
        aLine:SetTextColor(0.9, 0.9, 0.9, 1)
        aLine:Show()
        y = y - (aLine:GetStringHeight() + 14)
      end
    end

    if not any then
      local no = GetLine(1)
      no:ClearAllPoints()
      no:SetPoint("TOPLEFT", faqContainer, "TOPLEFT", 0, 0)
      no:SetWidth(width)
      no:SetText("No results.")
      local f, _, flags = no:GetFont()
      no:SetFont(f, 13, flags)
      no:Show()

      HideUnused(2)
      HideUnusedDividers(1)
      faqContainer:SetHeight(40)
      return
    end

    HideUnused(lineIndex)
    HideUnusedDividers(dividerIndex)
    faqContainer:SetHeight(math.max(40, -y + 8))
  end

  local function UpdateAboutFAQLayout()
    if not aboutContent or not faqContainer then return end
    if editor and editor.aboutSection and editor.aboutSection ~= "FAQ" then return end
    local h = faqContainer:GetHeight() or 400
    if editor and editor.SetAboutContentHeight then
      editor:SetAboutContentHeight(math.max(520, math.floor(h + 120)))
    end
  end

  editor.UpdateFAQText = UpdateFAQText
  editor.UpdateAboutFAQLayout = UpdateAboutFAQLayout

  SafeHookScript(aboutFAQFrame, "OnShow", function()
    UpdateFAQText()
    UpdateAboutFAQLayout()
  end)

  SafeHookScript(aboutContent, "OnSizeChanged", function()
    UpdateFAQText()
    UpdateAboutFAQLayout()
  end)

  faqSearchBox:SetScript("OnTextChanged", function()
    UpdateFAQText()
    UpdateAboutFAQLayout()
  end)
  faqSearchBox:SetScript("OnEscapePressed", function(self)
    self:ClearFocus()
  end)

  UpdateFAQText()
  UpdateAboutFAQLayout()
end

INTERNAL_API.LIDCOUNCIL_CreateAboutFAQSection_Impl = CreateAboutFAQSection
