--[[ UI/Filters.lua - left rail: search, type filter, buildable toggle, sort (spec F2). ]]

local _, ns = ...
local S = ns.Style
local W = ns.Widgets
ns.UI = ns.UI or {}
local UI = ns.UI

local function flt()
  ns.db.settings.lastFilters = ns.db.settings.lastFilters or {}
  return ns.db.settings.lastFilters
end

function UI.BuildFilters(rail)
  local y = -S.pad

  local head = W.Text(rail, S.size.small, S.gold)
  head:SetPoint("TOPLEFT", S.pad, y)
  head:SetText("SEARCH")
  y = y - 16

  local search = CreateFrame("EditBox", nil, rail, "BackdropTemplate")
  search:SetAutoFocus(false)
  search:SetPoint("TOPLEFT", S.pad, y)
  search:SetPoint("RIGHT", -S.pad, 0)
  search:SetHeight(22)
  search:SetFont(S.font, S.size.small, "")
  search:SetTextColor(unpack(S.text))
  search:SetBackdrop({ bgFile = "Interface\\Buttons\\WHITE8x8",
    edgeFile = "Interface\\Buttons\\WHITE8x8", edgeSize = 1 })
  search:SetBackdropColor(0, 0, 0, 0.6)
  search:SetBackdropBorderColor(unpack(S.border))
  search:SetTextInsets(6, 6, 0, 0)
  search:SetScript("OnTextChanged", function(self, user)
    if not user then return end
    flt().search = self:GetText():lower()
    if UI.ResetGridScroll then UI.ResetGridScroll() end
    UI.RefreshGrid()
  end)
  search:SetScript("OnEscapePressed", function(self) self:ClearFocus() end)
  y = y - 34

  local typeHead = W.Text(rail, S.size.small, S.gold)
  typeHead:SetPoint("TOPLEFT", S.pad, y)
  typeHead:SetText("TYPE")
  y = y - 20

  local types = { {"all","All"}, {"house","Full Layout"}, {"interior","Interior"},
                  {"exterior","Exterior"}, {"room","Room"} }
  UI.typeButtons = {}
  for _, t in ipairs(types) do
    local key, label = t[1], t[2]
    local b = W.Button(rail, label, function()
      flt().type = key
      for k, btn in pairs(UI.typeButtons) do
        local active = (k == key)
        btn.text:SetTextColor(active and S.gold[1] or S.text[1],
          active and S.gold[2] or S.text[2], active and S.gold[3] or S.text[3])
      end
      if UI.ResetGridScroll then UI.ResetGridScroll() end
      UI.RefreshGrid()
    end)
    b:SetPoint("TOPLEFT", S.pad, y)
    b:SetWidth(S.rail - 2 * S.pad)
    UI.typeButtons[key] = b
    y = y - 25
  end
  y = y - 8

  local sortHead = W.Text(rail, S.size.small, S.gold)
  sortHead:SetPoint("TOPLEFT", S.pad, y)
  sortHead:SetText("SORT")
  y = y - 20

  local sorts = { {"featured","Featured"}, {"newest","Newest"}, {"budgetAsc","Budget (low)"},
                  {"budgetDesc","Budget (high)"}, {"buildability","Buildable %"} }
  UI.sortButtons = {}
  for _, srt in ipairs(sorts) do
    local key, label = srt[1], srt[2]
    local b = W.Button(rail, label, function()
      flt().sort = key
      for k, btn in pairs(UI.sortButtons) do
        local active = (k == key)
        btn.text:SetTextColor(active and S.gold[1] or S.text[1],
          active and S.gold[2] or S.text[2], active and S.gold[3] or S.text[3])
      end
      if UI.ResetGridScroll then UI.ResetGridScroll() end
      UI.RefreshGrid()
    end)
    b:SetPoint("TOPLEFT", S.pad, y)
    b:SetWidth(S.rail - 2 * S.pad)
    UI.sortButtons[key] = b
    y = y - 25
  end
  y = y - 8

  local buildable = W.Button(rail, "[ ] Buildable 80%+", function(self)
    flt().buildable = not flt().buildable
    self.text:SetText((flt().buildable and "[x]" or "[ ]") .. " Buildable 80%+")
    if UI.ResetGridScroll then UI.ResetGridScroll() end
    UI.RefreshGrid()
  end)
  buildable:SetPoint("TOPLEFT", S.pad, y)
  buildable:SetWidth(S.rail - 2 * S.pad)
  y = y - 25

  -- The other axis of "can I build it": will my house take it. A level-1
  -- house holds none of the library's exteriors; this hides what would only
  -- fail, and the count that vanishes is itself the answer to "why level up".
  local fits = W.Button(rail, "[ ] Fits my house", function(self)
    flt().fits = not flt().fits
    self.text:SetText((flt().fits and "[x]" or "[ ]") .. " Fits my house")
    if UI.ResetGridScroll then UI.ResetGridScroll() end
    UI.RefreshGrid()
  end)
  fits:SetPoint("TOPLEFT", S.pad, y)
  fits:SetWidth(S.rail - 2 * S.pad)

  -- Submit call-to-action, pinned to the bottom of the rail. Every user is a
  -- potential builder, and the library only grows if they know that. WoW can't
  -- open links, so the address is a copyable box.
  local ctaHead = W.Text(rail, S.size.small, S.gold)
  ctaHead:SetPoint("BOTTOMLEFT", S.pad, 72)
  ctaHead:SetText("YOUR BUILD HERE?")

  local ctaText = W.Text(rail, S.size.tiny, S.textDim)
  ctaText:SetPoint("BOTTOMLEFT", S.pad, 30)
  ctaText:SetPoint("RIGHT", -S.pad, 0)
  ctaText:SetHeight(40)
  ctaText:SetJustifyV("TOP")
  ctaText:SetWordWrap(true)
  -- The Discord needs a role pick before #blueprints is visible; saying so
  -- here stops the link looking broken to anyone who follows it.
  ctaText:SetText("Send a share code and your name goes on it. "
    .. "Join, pick a role, then post in #blueprints.")

  local ctaBox = W.CopyBox(rail, S.rail - 2 * S.pad)
  ctaBox:SetPoint("BOTTOMLEFT", S.pad, S.pad)
  ctaBox:SetValue(ns.SUBMIT_URL or "curseforge.com/wow/addons/blueprintbazaar")

  -- Restore persisted filter state into the controls (filters survive /reload;
  -- without this the grid filters silently while every button looks inactive)
  local saved = flt()
  if saved.search and saved.search ~= "" then search:SetText(saved.search) end
  local function paint(map, activeKey)
    for k, btn in pairs(map) do
      local active = (k == activeKey)
      btn.text:SetTextColor(active and S.gold[1] or S.text[1],
        active and S.gold[2] or S.text[2], active and S.gold[3] or S.text[3])
    end
  end
  paint(UI.typeButtons, saved.type or "all")
  paint(UI.sortButtons, saved.sort or "featured")
  if saved.buildable then buildable.text:SetText("[x] Buildable 80%+") end
  if saved.fits then fits.text:SetText("[x] Fits my house") end
end
