-- HousingDecorGuide/UI/Projects/HDG_FloorSwitcher.lua
-- Vertical stack of floor tabs (F1, F2, ...) in the top-right of the architect canvas.
-- Selecting a floor calls onFloorSelected and updates state.projects.ui.selectedFloor
-- via Store.SetUIField (which routes through HDG.Store:SetProjectUI + QueueSave).

local _, privateDB = ...
local Store = privateDB.HDG_ProjectsStore

local M = {}

local TAB_HEIGHT = 22
local TAB_WIDTH  = 36

function M:Create(parent)
    if self.frame then return self.frame end
    self.parent = parent
    self.tabs = {}
    self.onFloorSelected = nil

    local frame = CreateFrame("Frame", nil, parent)
    frame:SetSize(TAB_WIDTH + 4, 200)
    frame:SetPoint("TOPRIGHT", parent, "TOPRIGHT", -8, -8)
    self.frame = frame

    return frame
end

local function _maxFloorFor(houseID)
    if not houseID then return 1 end
    return math.max(1, Store.GetNumFloors(houseID))
end

function M:Refresh(houseID, currentFloor)
    if not self.frame then return end
    local maxFloor = _maxFloorFor(houseID)

    -- Hide existing tabs not used this round
    for _, t in ipairs(self.tabs) do t:Hide() end

    -- Render newest floor at top, working down to F1
    for floor = maxFloor, 1, -1 do
        local idx = maxFloor - floor + 1
        local tab = self.tabs[idx]
        if not tab then
            tab = CreateFrame("Button", nil, self.frame)
            tab:SetSize(TAB_WIDTH, TAB_HEIGHT)
            tab.bg = tab:CreateTexture(nil, "BACKGROUND")
            tab.bg:SetAllPoints()
            tab.label = tab:CreateFontString(nil, "OVERLAY", "GameFontNormalSmall")
            tab.label:SetPoint("CENTER")
            self.tabs[idx] = tab
        end

        tab:ClearAllPoints()
        tab:SetPoint("TOPRIGHT", self.frame, "TOPRIGHT", 0, -(idx - 1) * (TAB_HEIGHT + 2))
        tab.label:SetText("F" .. floor)

        if floor == currentFloor then
            tab.bg:SetColorTexture(0.96, 0.80, 0.36, 0.4)
            tab.label:SetTextColor(1, 1, 0.85, 1)
        else
            tab.bg:SetColorTexture(0, 0, 0, 0.5)
            tab.label:SetTextColor(0.6, 0.7, 0.8, 1)
        end

        local capturedFloor = floor
        tab:SetScript("OnClick", function()
            Store.SetUIField("selectedFloor", capturedFloor)
            if self.onFloorSelected then self.onFloorSelected(capturedFloor) end
        end)

        tab:Show()
    end
end

function M:SetOnFloorSelected(fn)
    self.onFloorSelected = fn
end

privateDB.HDG_FloorSwitcher = M
