-- HousingDecorGuide/UI/Projects/HDG_ProjectsLanding.lua
-- The default sub-view of the Projects tab. Shows:
--   - Empty state with "Capture my house" CTA when no house is captured.
--   - Raw list of captured rooms (shape, floor, door count) when captured.

local _, privateDB = ...

local IDs      = privateDB.HDG_ProjectsIDs
local Store    = privateDB.HDG_ProjectsStore
local Capture  = privateDB.HDG_TopologyCapture

-- HDG_EventBus lives on the HDG global (HDG.EventBus) and uses Register/Trigger
local function _EventBus()
    local g = _G.HousingDecorGuide
    return g and g.EventBus
end

local M = {}

local function _currentHouseID()
    if Capture and Capture.GetCurrentHouseID then
        return Capture.GetCurrentHouseID()
    end
    -- Fallback for cold loads where Capture isn't yet ready
    local faction = UnitFactionGroup("player")
    if faction == "Alliance" then return "house:alliance" end
    if faction == "Horde"    then return "house:horde" end
    return nil
end

local function _hasRooms(houseID)
    if not houseID then return false end
    local rooms = Store.GetRoomsForHouse(houseID)
    return #rooms > 0
end

function M:_BuildEmptyState(parent)
    local f = CreateFrame("Frame", nil, parent)
    f:SetAllPoints(parent)

    local title = f:CreateFontString(nil, "OVERLAY", "GameFontNormalLarge")
    title:SetPoint("CENTER", f, "CENTER", 0, 40)
    title:SetText("No house captured yet")
    title:SetTextColor(0.96, 0.80, 0.36, 1)

    local sub = f:CreateFontString(nil, "OVERLAY", "GameFontHighlight")
    sub:SetPoint("TOP", title, "BOTTOM", 0, -8)
    sub:SetText("Visit your house, then click below to capture its layout.")
    sub:SetTextColor(0.6, 0.7, 0.8, 1)

    local btn = CreateFrame("Button", nil, f, "UIPanelButtonTemplate")
    btn:SetSize(180, 32)
    btn:SetPoint("TOP", sub, "BOTTOM", 0, -16)
    btn:SetText("Capture my house")

    local statusText = f:CreateFontString(nil, "OVERLAY", "GameFontDisableSmall")
    statusText:SetPoint("TOP", btn, "BOTTOM", 0, -8)

    local function _refreshButton()
        local available = C_HouseEditor and C_HouseEditor.IsHouseEditorStatusAvailable()
        if available then
            btn:Enable()
            statusText:SetText("")
        else
            btn:Disable()
            statusText:SetText("Visit your house to enable capture.")
        end
    end

    btn:SetScript("OnClick", function()
        local ok, err = Capture.CaptureAllFloors()
        if not ok and err then statusText:SetText(err) end
    end)

    f:SetScript("OnShow", _refreshButton)
    f:RegisterEvent("HOUSE_EDITOR_AVAILABILITY_CHANGED")
    f:SetScript("OnEvent", _refreshButton)
    _refreshButton()

    return f
end

function M:_BuildRoomList(parent)
    local f = CreateFrame("Frame", nil, parent)
    f:SetAllPoints(parent)

    local title = f:CreateFontString(nil, "OVERLAY", "GameFontNormal")
    title:SetPoint("TOPLEFT", f, "TOPLEFT", 12, -12)
    title:SetText("Captured rooms")
    title:SetTextColor(0.96, 0.80, 0.36, 1)

    local rescanBtn = CreateFrame("Button", nil, f, "UIPanelButtonTemplate")
    rescanBtn:SetSize(120, 24)
    rescanBtn:SetPoint("TOPRIGHT", f, "TOPRIGHT", -12, -10)
    rescanBtn:SetText("Re-capture")
    rescanBtn:SetScript("OnClick", function()
        Capture.CaptureAllFloors()
    end)

    local scrollContainer = CreateFrame("ScrollFrame", nil, f, "UIPanelScrollFrameTemplate")
    scrollContainer:SetPoint("TOPLEFT", title, "BOTTOMLEFT", 0, -8)
    scrollContainer:SetPoint("BOTTOMRIGHT", f, "BOTTOMRIGHT", -28, 8)

    local content = CreateFrame("Frame", nil, scrollContainer)
    content:SetSize(700, 1)
    scrollContainer:SetScrollChild(content)

    f.content = content

    function f:Refresh()
        for _, c in ipairs({ content:GetChildren() }) do c:Hide(); c:SetParent(nil) end

        local houseID = _currentHouseID()
        if not houseID then return end
        local entries = Store.GetRoomsForHouse(houseID)
        table.sort(entries, function(a, b)
            local pa = IDs.parsePath(a.id) or {}
            local pb = IDs.parsePath(b.id) or {}
            if pa.floor ~= pb.floor then return (pa.floor or 0) < (pb.floor or 0) end
            return a.id < b.id
        end)

        local y = -4
        for _, entry in ipairs(entries) do
            local row = CreateFrame("Frame", nil, content)
            row:SetSize(700, 24)
            row:SetPoint("TOPLEFT", content, "TOPLEFT", 4, y)

            local parsed = IDs.parsePath(entry.id) or {}
            local fp = entry.room.fingerprint or {}

            local txt = row:CreateFontString(nil, "OVERLAY", "GameFontNormalSmall")
            txt:SetPoint("LEFT", row, "LEFT", 0, 0)
            txt:SetText(string.format("F%d  %-22s  shape=%-18s degree=%d  doors=[%s]",
                parsed.floor or 0,
                "(room " .. (parsed.roomShortID or "?") .. ")",
                tostring(entry.room.shape or "?"),
                fp.degree or 0,
                table.concat(fp.doors or {}, ",")))
            y = y - 24
        end
        content:SetHeight(math.max(1, -y))
    end

    return f
end

function M:Create(parent)
    self.parent = parent
    self.empty = self:_BuildEmptyState(parent)
    self.list  = self:_BuildRoomList(parent)
    self.empty:Hide()
    self.list:Hide()

    local bus = _EventBus()
    if bus and bus.Register then
        bus:Register("HDG_PROJECTS_TOPOLOGY_UPDATED", function() self:Refresh() end)
        bus:Register("HDG_PROJECTS_CAPTURE_COMPLETE",  function() self:Refresh() end)
    end

    return self
end

function M:Show()
    self:Refresh()
end

function M:Hide()
    if self.empty then self.empty:Hide() end
    if self.list  then self.list:Hide()  end
end

function M:Refresh()
    local houseID = _currentHouseID()
    if _hasRooms(houseID) then
        self.empty:Hide()
        self.list:Show()
        self.list:Refresh()
    else
        self.list:Hide()
        self.empty:Show()
    end
end

privateDB.HDG_ProjectsLanding = M
