local _, ns = ...

local UIC = {
  THEME_MARBLE = "Interface\\FrameGeneral\\UI-Background-Marble",
  THEME_DARK = "Interface\\DialogFrame\\UI-DialogBox-Background-Dark",
  THEME_BORDER = "Interface\\Tooltips\\UI-Tooltip-Border",
  THEME_FLAT = "Interface\\Buttons\\WHITE8X8",
  THEME_HOUSING_BG_TGA = "Interface\\AddOns\\VamLaxPowerCrafter\\Media\\HousingBackdrop.tga",
  THEME_HOUSING_BG_PNG = "Interface\\AddOns\\VamLaxPowerCrafter\\Media\\HousingBackdrop.png",
  THEME_HOUSING_BG_JPG = "Interface\\AddOns\\VamLaxPowerCrafter\\Media\\HousingBackdrop.jpg",
  BASE_FRAME_WIDTH = 1140,
  BASE_FRAME_HEIGHT = 700,
}

local function SetAddonIcon(texture)
  texture:SetTexture("Interface\\AddOns\\VamLaxPowerCrafter\\Media\\DecorDropsPortraitIcon_new.png")
  texture:SetTexCoord(0.08, 0.92, 0.08, 0.92)
end

local LEFT_PAGES = {
  { key = "instances", label = "Raids & Dungeons", icon = "Interface\\AddOns\\VamLaxPowerCrafter\\Media\\DungeonRaidPortal.png", railY = -6 },
  { key = "professions", label = "Professions", icon = "Interface\\Icons\\INV_Inscription_Tradeskill01", railY = -49 },
  { key = "vendor", label = "Vendor", icon = "Interface\\Icons\\INV_Misc_Coin_02", railY = -92 },
  { key = "achievement", label = "Achievement", icon = "Interface\\Icons\\Achievement_Quests_Completed_08", railY = -135 },
  { key = "quest", label = "Quest", icon = "Interface\\GossipFrame\\AvailableQuestIcon", railY = -178 },
  { key = "reputation", label = "Reputation", icon = "Interface\\Icons\\Achievement_Reputation_01", railY = -221 },
  { key = "endeavor", label = "Endeavor", icon = "Interface\\Icons\\INV_Misc_Note_01", railY = -264 },
  { key = "promotion", label = "Promotional", icon = "Interface\\Icons\\INV_Misc_Coin_17", railY = -307 },
}

local BOTTOM_TABS = {
  { key = "Info", label = "Info" },
  { key = "Features", label = "Features" },
  { key = "Settings", label = "Settings" },
}

local function CreateModeButton(parent, offsetY, texturePath, tooltipText, onClick)
  local btn = CreateFrame("Button", nil, parent, "BackdropTemplate")
  btn:SetSize(40, 40)
  btn:SetPoint("TOPLEFT", 2, offsetY)
  btn:SetBackdrop({
    bgFile = UIC.THEME_DARK,
    edgeFile = UIC.THEME_BORDER,
    edgeSize = 10,
    insets = { left = 2, right = 2, top = 2, bottom = 2 },
  })
  btn:SetBackdropColor(0.08, 0.08, 0.08, 0.95)
  btn:SetBackdropBorderColor(0.44, 0.42, 0.38, 0.90)
  btn:SetHighlightTexture(UIC.THEME_FLAT)
  if btn:GetHighlightTexture() then
    btn:GetHighlightTexture():SetAllPoints()
    btn:GetHighlightTexture():SetVertexColor(1.00, 0.82, 0.20, 0.08)
  end

  btn.selected = btn:CreateTexture(nil, "ARTWORK")
  btn.selected:SetAllPoints()
  btn.selected:SetTexture(UIC.THEME_FLAT)
  btn.selected:SetVertexColor(1.00, 0.82, 0.20, 0.28)
  btn.selected:Hide()

  btn.icon = btn:CreateTexture(nil, "ARTWORK")
  btn.icon:SetPoint("TOPLEFT", 6, -6)
  btn.icon:SetPoint("BOTTOMRIGHT", -6, 6)
  btn.icon:SetTexture(texturePath)
  btn.icon:SetTexCoord(0.08, 0.92, 0.08, 0.92)

  btn:SetScript("OnClick", onClick)
  btn:SetScript("OnEnter", function(self)
    GameTooltip:SetOwner(self, "ANCHOR_RIGHT")
    GameTooltip:AddLine(tooltipText)
    GameTooltip:Show()
  end)
  btn:SetScript("OnLeave", GameTooltip_Hide)

  return btn
end

local function CreateBottomTab(parent, label, onClick)
  local tab = CreateFrame("Button", nil, parent, "PanelTabButtonTemplate")
  tab:SetText(label)
  tab:SetScript("OnClick", onClick)
  if PanelTemplates_TabResize and tab.GetFontString and tab:GetFontString() then
    PanelTemplates_TabResize(tab, 0, nil, 100, nil, tab:GetFontString():GetStringWidth())
  end
  tab.glow = tab:CreateTexture(nil, "ARTWORK", nil, 1)
  tab.glow:SetPoint("TOPLEFT", 5, -4)
  tab.glow:SetPoint("BOTTOMRIGHT", -5, 3)
  tab.glow:SetTexture(UIC.THEME_FLAT)
  tab.glow:SetVertexColor(1.00, 0.82, 0.18, 0.08)
  tab.glow:Hide()
  return tab
end

local function SetBottomTabVisual(tab, active)
  if not tab then return end
  if PanelTemplates_SelectTab and PanelTemplates_DeselectTab then
    if active then
      PanelTemplates_SelectTab(tab)
    else
      PanelTemplates_DeselectTab(tab)
    end
  end
  if tab.glow then
    tab.glow:SetShown(active)
  end
end

local function EnsureBackdrop(texture)
  local ok = texture:SetTexture(UIC.THEME_HOUSING_BG_TGA)
  if not ok then ok = texture:SetTexture(UIC.THEME_HOUSING_BG_PNG) end
  if not ok then ok = texture:SetTexture(UIC.THEME_HOUSING_BG_JPG) end
  if not ok then texture:SetTexture(UIC.THEME_MARBLE) end
end

function ns.ApplyFrameScaleAndClamp(frame)
  if not frame then return end
  if frame.SetClampedToScreen then
    frame:SetClampedToScreen(true)
  end
end

function ns.ReflowMainFrame()
  if ns.MainFrame and ns.MainFrame:IsShown() then
    ns.ApplyFrameScaleAndClamp(ns.MainFrame)
  end
end

function ns.SetViewMode(frame, mode)
  if not frame then return end
  local valid = false
  for _, entry in ipairs(LEFT_PAGES) do
    if entry.key == mode then
      valid = true
      break
    end
  end
  frame.viewMode = valid and mode or "instances"

  if frame.leftTitle then
    for _, entry in ipairs(LEFT_PAGES) do
      if entry.key == frame.viewMode then
        frame.leftTitle:SetText(entry.label)
        break
      end
    end
  end

  if frame.railButtons then
    for key, btn in pairs(frame.railButtons) do
      local active = key == frame.viewMode
      btn.selected:SetShown(active)
      if active then
        btn:SetBackdropBorderColor(1.00, 0.82, 0.20, 1.00)
      else
        btn:SetBackdropBorderColor(0.44, 0.42, 0.38, 0.90)
      end
    end
  end

  if frame.skeletonTitle then
    frame.skeletonTitle:SetText("Skeleton: " .. (frame.leftTitle and frame.leftTitle:GetText() or "Page"))
  end
  if frame.skeletonSubtitle then
    frame.skeletonSubtitle:SetText("Item and category logic intentionally removed for redesign.")
  end
  if frame.middleBodyText then
    frame.middleBodyText:SetText("Middle column skeleton panel for " .. (frame.leftTitle and frame.leftTitle:GetText() or "page") .. ".")
  end
  if frame.column3Text then
    frame.column3Text:SetText(
      "Column 3 scroll area\n\n"
      .. "Independent mouse wheel and scroll child.\n\n"
      .. "Current page: " .. (frame.leftTitle and frame.leftTitle:GetText() or "Unknown")
    )
    if frame.column3Content then
      frame.column3Content:SetHeight(math.max(1, frame.column3Text:GetStringHeight() + 20))
    end
    if frame.column3Scroll then
      frame.column3Scroll:SetVerticalScroll(0)
    end
  end

  if frame.leftListText then
    frame.leftListText:SetText("No categories (skeleton build).")
  end
end

function ns.SetActiveBottomTab(frame, tabKey)
  if not frame then return end
  frame.activeBottomTab = tabKey or ""

  local showInfo = frame.activeBottomTab == "Info"
  local showFeatures = frame.activeBottomTab == "Features"
  local showSettings = frame.activeBottomTab == "Settings"

  if frame.infoPanel then frame.infoPanel:SetShown(showInfo) end
  if frame.featuresPanel then frame.featuresPanel:SetShown(showFeatures) end
  if frame.settingsPanel then frame.settingsPanel:SetShown(showSettings) end

  SetBottomTabVisual(frame.infoTab, showInfo)
  SetBottomTabVisual(frame.featuresTab, showFeatures)
  SetBottomTabVisual(frame.settingsTab, showSettings)
end

function ns.CreateUI()
  local frame = CreateFrame("Frame", "VamLaxPowerCrafterMainFrame", UIParent, "PortraitFrameTemplate")
  frame:SetSize(UIC.BASE_FRAME_WIDTH, UIC.BASE_FRAME_HEIGHT)
  frame:SetPoint("CENTER")
  frame:SetToplevel(true)
  frame:SetFrameStrata("DIALOG")
  frame:SetFrameLevel(200)
  frame:SetMovable(true)
  frame:EnableMouse(true)
  frame:SetClampedToScreen(true)
  frame:RegisterForDrag("LeftButton")
  frame:SetScript("OnDragStart", frame.StartMoving)
  frame:SetScript("OnDragStop", function(self)
    self:StopMovingOrSizing()
    ns.ApplyFrameScaleAndClamp(self)
  end)
  frame:Hide()

  if UISpecialFrames then
    local found = false
    for _, name in ipairs(UISpecialFrames) do
      if name == "VamLaxPowerCrafterMainFrame" then
        found = true
        break
      end
    end
    if not found then
      table.insert(UISpecialFrames, "VamLaxPowerCrafterMainFrame")
    end
  end

  frame.bg = frame:CreateTexture(nil, "ARTWORK", nil, -8)
  frame.bg:SetAllPoints()
  EnsureBackdrop(frame.bg)
  frame.bg:SetTexCoord(0.02, 0.98, 0.04, 0.96)
  frame.bg:SetVertexColor(0.74, 0.72, 0.68, 1.00)

  frame.bgShade = frame:CreateTexture(nil, "ARTWORK", nil, -7)
  frame.bgShade:SetAllPoints()
  frame.bgShade:SetTexture(UIC.THEME_FLAT)
  frame.bgShade:SetVertexColor(0.08, 0.06, 0.04, 0.16)

  if frame.TitleText then
    frame.TitleText:SetText("Vamlax PowerCrafter")
  elseif frame.TitleContainer and frame.TitleContainer.TitleText then
    frame.TitleContainer.TitleText:SetText("Vamlax PowerCrafter")
  end

  frame.portrait = frame:CreateTexture(nil, "ARTWORK")
  SetAddonIcon(frame.portrait)
  frame.portrait:SetSize(56, 56)
  frame.portrait:SetPoint("TOPLEFT", -5, 7)

  frame.modeTabRail = CreateFrame("Frame", nil, frame)
  frame.modeTabRail:SetSize(44, 390)
  frame.modeTabRail:SetPoint("TOPRIGHT", frame, "TOPLEFT", -1, -82)

  frame.leftPanel = CreateFrame("Frame", nil, frame, "BackdropTemplate")
  frame.leftPanel:SetSize(280, 590)
  frame.leftPanel:SetPoint("TOPLEFT", 20, -82)
  frame.leftPanel:SetBackdrop({
    bgFile = UIC.THEME_MARBLE,
    edgeFile = UIC.THEME_BORDER,
    edgeSize = 12,
    insets = { left = 2, right = 2, top = 2, bottom = 2 },
  })
  frame.leftPanel:SetBackdropColor(0.18, 0.14, 0.10, 0.52)
  frame.leftPanel:SetBackdropBorderColor(0.88, 0.74, 0.46, 0.92)

  frame.leftTitle = frame.leftPanel:CreateFontString(nil, "OVERLAY", "GameFontNormal")
  frame.leftTitle:SetPoint("TOPLEFT", 12, -10)
  frame.leftTitle:SetText("Raids & Dungeons")
  frame.leftTitle:SetTextColor(0.98, 0.90, 0.74)

  frame.leftList = CreateFrame("Frame", nil, frame.leftPanel, "BackdropTemplate")
  frame.leftList:SetPoint("TOPLEFT", 10, -34)
  frame.leftList:SetPoint("BOTTOMRIGHT", -10, 10)
  frame.leftList:SetBackdrop({
    bgFile = UIC.THEME_DARK,
    edgeFile = UIC.THEME_BORDER,
    edgeSize = 10,
    insets = { left = 2, right = 2, top = 2, bottom = 2 },
  })
  frame.leftList:SetBackdropColor(0.05, 0.05, 0.05, 0.70)
  frame.leftList:SetBackdropBorderColor(0.56, 0.48, 0.36, 0.72)

  frame.leftListText = frame.leftList:CreateFontString(nil, "OVERLAY", "GameFontHighlightSmall")
  frame.leftListText:SetPoint("TOPLEFT", 10, -10)
  frame.leftListText:SetPoint("TOPRIGHT", -10, -10)
  frame.leftListText:SetJustifyH("LEFT")
  frame.leftListText:SetJustifyV("TOP")
  frame.leftListText:SetTextColor(0.90, 0.82, 0.64)
  frame.leftListText:SetText("No categories (skeleton build).")

  frame.rightPanel = CreateFrame("Frame", nil, frame, "BackdropTemplate")
  frame.rightPanel:SetSize(810, 590)
  frame.rightPanel:SetPoint("TOPLEFT", frame.leftPanel, "TOPRIGHT", 12, 0)
  frame.rightPanel:SetBackdrop({
    bgFile = UIC.THEME_MARBLE,
    edgeFile = UIC.THEME_BORDER,
    edgeSize = 12,
    insets = { left = 2, right = 2, top = 2, bottom = 2 },
  })
  frame.rightPanel:SetBackdropColor(0.18, 0.14, 0.10, 0.52)
  frame.rightPanel:SetBackdropBorderColor(0.88, 0.74, 0.46, 0.92)

  local rightColumnGap = 8
  local rightColumnInset = 8
  local rightColumnWidth = math.floor((810 - (rightColumnInset * 2) - rightColumnGap) / 2)

  frame.middlePanel = CreateFrame("Frame", nil, frame.rightPanel, "BackdropTemplate")
  frame.middlePanel:SetPoint("TOPLEFT", rightColumnInset, -56)
  frame.middlePanel:SetPoint("BOTTOMLEFT", rightColumnInset, 8)
  frame.middlePanel:SetWidth(rightColumnWidth)
  frame.middlePanel:SetBackdrop({
    bgFile = UIC.THEME_DARK,
    edgeFile = UIC.THEME_BORDER,
    edgeSize = 10,
    insets = { left = 2, right = 2, top = 2, bottom = 2 },
  })
  frame.middlePanel:SetBackdropColor(0.04, 0.04, 0.04, 0.80)
  frame.middlePanel:SetBackdropBorderColor(0.56, 0.48, 0.36, 0.72)

  frame.rightPanelColumn = CreateFrame("Frame", nil, frame.rightPanel, "BackdropTemplate")
  frame.rightPanelColumn:SetPoint("TOPLEFT", frame.middlePanel, "TOPRIGHT", rightColumnGap, 0)
  frame.rightPanelColumn:SetPoint("BOTTOMRIGHT", frame.rightPanel, "BOTTOMRIGHT", -rightColumnInset, 8)
  frame.rightPanelColumn:SetWidth(rightColumnWidth)
  frame.rightPanelColumn:SetBackdrop({
    bgFile = UIC.THEME_DARK,
    edgeFile = UIC.THEME_BORDER,
    edgeSize = 10,
    insets = { left = 2, right = 2, top = 2, bottom = 2 },
  })
  frame.rightPanelColumn:SetBackdropColor(0.04, 0.04, 0.04, 0.80)
  frame.rightPanelColumn:SetBackdropBorderColor(0.56, 0.48, 0.36, 0.72)

  frame.skeletonTitle = frame.middlePanel:CreateFontString(nil, "OVERLAY", "GameFontNormalLarge")
  frame.skeletonTitle:SetPoint("TOPLEFT", 12, -12)
  frame.skeletonTitle:SetTextColor(0.97, 0.88, 0.68)
  frame.skeletonTitle:SetText("Skeleton: Raids & Dungeons")

  frame.skeletonSubtitle = frame.middlePanel:CreateFontString(nil, "OVERLAY", "GameFontHighlightSmall")
  frame.skeletonSubtitle:SetPoint("TOPLEFT", frame.skeletonTitle, "BOTTOMLEFT", 0, -6)
  frame.skeletonSubtitle:SetTextColor(0.90, 0.82, 0.64)
  frame.skeletonSubtitle:SetText("Item and category logic intentionally removed for redesign.")

  frame.middleBodyText = frame.middlePanel:CreateFontString(nil, "OVERLAY", "GameFontHighlight")
  frame.middleBodyText:SetPoint("TOPLEFT", 12, -56)
  frame.middleBodyText:SetPoint("TOPRIGHT", -12, -56)
  frame.middleBodyText:SetJustifyH("LEFT")
  frame.middleBodyText:SetJustifyV("TOP")
  frame.middleBodyText:SetTextColor(0.90, 0.82, 0.64)
  frame.middleBodyText:SetText("Middle column skeleton panel.")

  frame.column3Title = frame.rightPanelColumn:CreateFontString(nil, "OVERLAY", "GameFontNormal")
  frame.column3Title:SetPoint("TOPLEFT", 12, -12)
  frame.column3Title:SetTextColor(0.97, 0.88, 0.68)
  frame.column3Title:SetText("Column 3")

  frame.column3Scroll = CreateFrame("ScrollFrame", "VamLaxPowerCrafterColumn3ScrollFrame", frame.rightPanelColumn, "UIPanelScrollFrameTemplate")
  frame.column3Scroll:SetPoint("TOPLEFT", 10, -34)
  frame.column3Scroll:SetPoint("BOTTOMRIGHT", -28, 10)
  frame.column3Scroll:EnableMouseWheel(true)

  frame.column3Content = CreateFrame("Frame", nil, frame.column3Scroll)
  frame.column3Content:SetSize(rightColumnWidth - 40, 1)
  frame.column3Scroll:SetScrollChild(frame.column3Content)

  frame.column3Text = frame.column3Content:CreateFontString(nil, "OVERLAY", "GameFontHighlightSmall")
  frame.column3Text:SetPoint("TOPLEFT", 0, 0)
  frame.column3Text:SetPoint("TOPRIGHT", 0, 0)
  frame.column3Text:SetJustifyH("LEFT")
  frame.column3Text:SetJustifyV("TOP")
  frame.column3Text:SetTextColor(0.90, 0.82, 0.64)
  frame.column3Text:SetText("Column 3 scroll area\\n\\nWheel support enabled.\\n\\nThis panel has its own scroll frame and independent scroll child anchor.")
  frame.column3Content:SetHeight(math.max(1, frame.column3Text:GetStringHeight() + 20))

  frame.column3Scroll:SetScript("OnMouseWheel", function(self, delta)
    local current = self:GetVerticalScroll() or 0
    local range = self:GetVerticalScrollRange() or 0
    local nextValue = current - ((tonumber(delta) or 0) * 28)
    if nextValue < 0 then
      nextValue = 0
    elseif nextValue > range then
      nextValue = range
    end
    self:SetVerticalScroll(nextValue)
  end)

  frame.infoPanel = CreateFrame("Frame", nil, frame.rightPanel, "BackdropTemplate")
  frame.infoPanel:SetPoint("TOPLEFT", 8, -56)
  frame.infoPanel:SetPoint("BOTTOMRIGHT", -8, 8)
  frame.infoPanel:SetBackdrop({ bgFile = UIC.THEME_DARK, edgeFile = UIC.THEME_BORDER, edgeSize = 10, insets = { left = 2, right = 2, top = 2, bottom = 2 } })
  frame.infoPanel:SetBackdropColor(0.04, 0.04, 0.04, 0.80)
  frame.infoPanel:SetBackdropBorderColor(0.56, 0.48, 0.36, 0.72)
  frame.infoPanel:Hide()
  frame.infoText = frame.infoPanel:CreateFontString(nil, "OVERLAY", "GameFontHighlight")
  frame.infoText:SetPoint("TOPLEFT", 12, -12)
  frame.infoText:SetPoint("TOPRIGHT", -12, -12)
  frame.infoText:SetJustifyH("LEFT")
  frame.infoText:SetJustifyV("TOP")
  frame.infoText:SetText("Info\n\nSkeleton UI build for Vamlax PowerCrafter.")

  frame.featuresPanel = CreateFrame("Frame", nil, frame.rightPanel, "BackdropTemplate")
  frame.featuresPanel:SetPoint("TOPLEFT", 8, -56)
  frame.featuresPanel:SetPoint("BOTTOMRIGHT", -8, 8)
  frame.featuresPanel:SetBackdrop({ bgFile = UIC.THEME_DARK, edgeFile = UIC.THEME_BORDER, edgeSize = 10, insets = { left = 2, right = 2, top = 2, bottom = 2 } })
  frame.featuresPanel:SetBackdropColor(0.04, 0.04, 0.04, 0.80)
  frame.featuresPanel:SetBackdropBorderColor(0.56, 0.48, 0.36, 0.72)
  frame.featuresPanel:Hide()
  frame.featuresText = frame.featuresPanel:CreateFontString(nil, "OVERLAY", "GameFontHighlight")
  frame.featuresText:SetPoint("TOPLEFT", 12, -12)
  frame.featuresText:SetPoint("TOPRIGHT", -12, -12)
  frame.featuresText:SetJustifyH("LEFT")
  frame.featuresText:SetJustifyV("TOP")
  frame.featuresText:SetText("Features\n\nCore page skeleton retained for redesign.")

  frame.settingsPanel = CreateFrame("Frame", nil, frame.rightPanel, "BackdropTemplate")
  frame.settingsPanel:SetPoint("TOPLEFT", 8, -56)
  frame.settingsPanel:SetPoint("BOTTOMRIGHT", -8, 8)
  frame.settingsPanel:SetBackdrop({ bgFile = UIC.THEME_DARK, edgeFile = UIC.THEME_BORDER, edgeSize = 10, insets = { left = 2, right = 2, top = 2, bottom = 2 } })
  frame.settingsPanel:SetBackdropColor(0.04, 0.04, 0.04, 0.80)
  frame.settingsPanel:SetBackdropBorderColor(0.56, 0.48, 0.36, 0.72)
  frame.settingsPanel:Hide()
  frame.settingsText = frame.settingsPanel:CreateFontString(nil, "OVERLAY", "GameFontHighlight")
  frame.settingsText:SetPoint("TOPLEFT", 12, -12)
  frame.settingsText:SetPoint("TOPRIGHT", -12, -12)
  frame.settingsText:SetJustifyH("LEFT")
  frame.settingsText:SetJustifyV("TOP")
  frame.settingsText:SetText("Settings\n\nSettings page restored as a clean skeleton.")

  frame.railButtons = {}
  for _, page in ipairs(LEFT_PAGES) do
    frame.railButtons[page.key] = CreateModeButton(frame.modeTabRail, page.railY, page.icon, page.label, function()
      ns.SetViewMode(frame, page.key)
    end)
  end

  frame.infoTab = CreateBottomTab(frame, "Info", function()
    ns.SetActiveBottomTab(frame, "Info")
  end)
  frame.featuresTab = CreateBottomTab(frame, "Features", function()
    ns.SetActiveBottomTab(frame, "Features")
  end)
  frame.settingsTab = CreateBottomTab(frame, "Settings", function()
    ns.SetActiveBottomTab(frame, "Settings")
  end)

  frame.infoTab:SetPoint("TOPRIGHT", frame, "BOTTOMRIGHT", -26, 1)
  frame.featuresTab:SetPoint("RIGHT", frame.infoTab, "LEFT", -8, 0)
  frame.settingsTab:SetPoint("RIGHT", frame.featuresTab, "LEFT", -8, 0)

  ns.MainFrame = frame
  ns.SetViewMode(frame, "instances")
  ns.SetActiveBottomTab(frame, nil)
end

function ns.RefreshUI()
  if not ns.MainFrame then
    return
  end
  ns.SetViewMode(ns.MainFrame, ns.MainFrame.viewMode or "instances")
end
