-- ============================================================
-- Komo Hold'Em — Launcher window
-- Views: HOME (logo, host button, table list) and LOBBY (host
-- waiting room: seats, ready count, start/cancel). Hitting Host
-- now swaps to the lobby instead of only announcing.
-- ============================================================
local _, KH = ...
KH.Launcher = {}
local Launcher = KH.Launcher
local UI = KH.UI
local C  = KH.COLORS

local WIDTH, HEIGHT = 420, 560
local MEDIA = "Interface\\AddOns\\KomoHoldEm\\Media\\"
local FONT  = "Fonts\\FRIZQT__.TTF"
local MAX_ROWS  = 5
local MAX_SEATS = 8

local function setFont(fs, size, flags)
    fs:SetFont(FONT, size, flags or "")
end

function Launcher:Create()
    if self.frame then return self.frame end

    local f = UI.CreatePanel(UIParent, WIDTH, HEIGHT)
    f:SetBackdropColor(0, 0, 0, 0)
    f:SetBackdropBorderColor(0, 0, 0, 0)
    f:SetFrameStrata("HIGH")
    f:SetPoint("CENTER", KH.db.window.x, KH.db.window.y)
    f:SetScale(KH.db.settings.scale)
    f:SetMovable(true)
    f:EnableMouse(true)
    f:SetClampedToScreen(true)
    f:RegisterForDrag("LeftButton")
    f:SetScript("OnDragStart", f.StartMoving)
    f:SetScript("OnDragStop", function()
        f:StopMovingOrSizing()
        local cx, cy = f:GetCenter()
        local px, py = UIParent:GetCenter()
        KH.db.window.x, KH.db.window.y = cx - px, cy - py
    end)
    f:Hide()

    -- background art
    local bg = f:CreateTexture(nil, "BACKGROUND", nil, 1)
    bg:SetAllPoints()
    bg:SetTexture(MEDIA .. "LauncherBG")

    -- titlebar
    local title = f:CreateFontString(nil, "OVERLAY")
    setFont(title, 13, "OUTLINE")
    title:SetPoint("TOPLEFT", 14, -13)
    title:SetText("KOMO HOLD'EM")
    title:SetTextColor(unpack(C.GOLD))

    local close = CreateFrame("Button", nil, f, "UIPanelCloseButton")
    close:SetPoint("TOPRIGHT", -4, -4)
    close:SetScript("OnClick", function() f:Hide() end)

    local back = UI.CreateBlueButton(f, 56, 20, "Back")
    back:SetPoint("TOPRIGHT", -30, -7)
    setFont(back.label, 11, "")
    back:SetScript("OnClick", function() Launcher:ShowHome() end)
    back:Hide()
    self.backBtn = back

    local titleLine = f:CreateTexture(nil, "ARTWORK")
    titleLine:SetPoint("TOPLEFT", 1, -34)
    titleLine:SetPoint("TOPRIGHT", -1, -34)
    titleLine:SetHeight(1)
    titleLine:SetColorTexture(0.165, 0.176, 0.212, 1)

    -- footer (shared by both views)
    local footLine = f:CreateTexture(nil, "ARTWORK")
    footLine:SetPoint("BOTTOMLEFT", 1, 34)
    footLine:SetPoint("BOTTOMRIGHT", -1, 34)
    footLine:SetHeight(1)
    footLine:SetColorTexture(0.165, 0.176, 0.212, 1)

    local ver = f:CreateFontString(nil, "OVERLAY")
    setFont(ver, 11)
    ver:SetPoint("BOTTOMLEFT", 14, 12)
    ver:SetText("v" .. KH.VERSION)
    ver:SetTextColor(0.604, 0.624, 0.663)

    local cmds = f:CreateFontString(nil, "OVERLAY")
    setFont(cmds, 11)
    cmds:SetPoint("BOTTOMRIGHT", -14, 12)
    cmds:SetText("|cfffad990/kh|r |cffffffffto open ·|r |cfffad990/kh host|r |cffffffff·|r |cfffad990/kh join|r")

    self.frame = f
    self:BuildHome(f)
    self:BuildConfig(f)
    self:BuildLobby(f)
    return f
end

-- ============================================================
-- CONFIG VIEW (host settings)
-- ============================================================
function Launcher:BuildConfig(f)
    local cfg = CreateFrame("Frame", nil, f)
    cfg:SetPoint("TOPLEFT", 0, -35)
    cfg:SetPoint("BOTTOMRIGHT", 0, 35)
    cfg:Hide()
    self.configView = cfg

    local W = WIDTH - 32

    local title = cfg:CreateFontString(nil, "OVERLAY")
    setFont(title, 18, "")
    title:SetPoint("TOP", 0, -12)
    title:SetText("Host a Table")
    title:SetTextColor(1, 1, 1)

    local function fieldLabel(text, y)
        local l = cfg:CreateFontString(nil, "OVERLAY")
        setFont(l, 11, "")
        l:SetPoint("TOPLEFT", 16, y)
        l:SetText(text)
        l:SetTextColor(unpack(C.TEXT))
        return l
    end

    -- table name
    fieldLabel("TABLE NAME", -46)
    self.cfgName = UI.CreateEditBox(cfg, W, 32)
    self.cfgName:SetPoint("TOP", 0, -62)

    -- stakes
    fieldLabel("TABLE STAKES", -106)
    self.cfgStakes = UI.CreateSegmented(cfg, W, 32,
        { "Imitation Gold Chips", "WoW Gold" }, 1,
        function(ix) Launcher:OnStakesChanged(ix) end)
    self.cfgStakes:SetPoint("TOP", 0, -122)

    -- amount
    self.cfgAmountLabel = fieldLabel("STARTING CHIP AMOUNT", -166)
    self.cfgAmount = UI.CreateEditBox(cfg, W, 32, true)
    self.cfgAmount:SetPoint("TOP", 0, -182)

    -- seats
    fieldLabel("SEATS", -226)
    self.cfgSeats = UI.CreateSegmented(cfg, W, 32, { "4", "6", "8" }, 2)
    self.cfgSeats:SetPoint("TOP", 0, -242)

    -- turn timer
    fieldLabel("TURN TIMER", -286)
    self.cfgTimer = UI.CreateSegmented(cfg, W, 32,
        { "Relaxed · 60s", "Normal · 30s", "Fast · 15s" }, 2)
    self.cfgTimer:SetPoint("TOP", 0, -302)

    -- gold disclaimer
    local note = UI.CreatePanel(cfg, W, 64)
    note:SetPoint("TOP", 0, -348)
    note:SetBackdropColor(0.13, 0.10, 0.03, 0.9)
    note:SetBackdropBorderColor(0.847, 0.631, 0.227, 0.8)
    note.text = note:CreateFontString(nil, "OVERLAY")
    setFont(note.text, 11, "")
    note.text:SetPoint("TOPLEFT", 12, -10)
    note.text:SetPoint("BOTTOMRIGHT", -12, 10)
    note.text:SetJustifyH("LEFT")
    note.text:SetJustifyV("TOP")
    note.text:SetText("|cfff6dd85Real WoW gold table.|r |cffe8c96aThe buy-in is paid in WoW gold. If you lose, you owe the gold you lost. Every player sees this notice before taking a seat.|r")
    note:Hide()
    self.cfgGoldNote = note

    -- open table
    local open = UI.CreateGoldButton(cfg, W, 42, "Open Table")
    open:SetPoint("BOTTOM", 0, 14)
    setFont(open.label, 15, "")
    open.label:SetTextColor(0.09, 0.075, 0.04)
    open:SetScript("OnClick", function() Launcher:OpenTableFromConfig() end)
end

function Launcher:OnStakesChanged(ix)
    if ix == 2 then
        self.cfgAmountLabel:SetText("BUY-IN (WOW GOLD)")
        self.cfgAmount:SetText("500")
        self.cfgGoldNote:Show()
        KH.Sounds:Play("GOLD_NOTICE")
    else
        self.cfgAmountLabel:SetText("STARTING CHIP AMOUNT")
        self.cfgAmount:SetText("2500")
        self.cfgGoldNote:Hide()
    end
end

function Launcher:OpenTableFromConfig()
    local name = self.cfgName:GetText()
    if name == "" then name = UnitName("player") .. "'s Table" end

    local stakes = self.cfgStakes:GetSelected() == 2 and "gold" or "chips"
    local amount = self.cfgAmount:GetNumber()
    if stakes == "gold" then
        amount = math.max(1, amount == 0 and 500 or amount)
    else
        amount = math.max(100, amount == 0 and 2500 or amount)
    end

    local seatOpts  = { 4, 6, 8 }
    local timerOpts = { 60, 30, 15 }

    KH.Sounds:Play("UI_CLICK")
    KH.Lobby:HostTable({
        name   = name,
        stakes = stakes,
        amount = amount,
        seats  = seatOpts[self.cfgSeats:GetSelected()],
        timer  = timerOpts[self.cfgTimer:GetSelected()],
    })
    if KH.Lobby.mine then self:ShowLobby() end
end

function Launcher:ShowConfig()
    self:Create()
    self:HideAllViews()
    self.frame:SetHeight(HEIGHT)
    self.configView:Show()
    self.backBtn:Show()
    -- fresh defaults each visit
    self.cfgName:SetText(UnitName("player") .. "'s Table")
    self.cfgName:ClearFocus()
    if self.cfgStakes:GetSelected() == 2 then
        self.cfgAmount:SetText("500")
        self.cfgGoldNote:Show()
    else
        self.cfgAmount:SetText("2500")
        self.cfgGoldNote:Hide()
    end
end

-- ============================================================
-- HOME VIEW
-- ============================================================
function Launcher:BuildHome(f)
    local home = CreateFrame("Frame", nil, f)
    home:SetPoint("TOPLEFT", 0, -35)
    home:SetPoint("BOTTOMRIGHT", 0, 35)
    self.homeView = home

    local logo = home:CreateTexture(nil, "ARTWORK")
    logo:SetSize(300, 131)
    logo:SetPoint("TOP", 0, -18)
    logo:SetTexture(MEDIA .. "LogoFull")
    logo:SetTexCoord(0, 0.75390625, 0, 0.658203125)

    local hostBtn = UI.CreateGoldButton(home, WIDTH - 32, 44, "Host a Table")
    hostBtn:SetPoint("TOP", 0, -170)
    setFont(hostBtn.label, 15, "")
    hostBtn.label:SetTextColor(0.09, 0.075, 0.04)
    hostBtn:SetScript("OnClick", function()
        KH.Sounds:Play("UI_CLICK")
        Launcher:ShowConfig()
    end)

    local div = home:CreateFontString(nil, "OVERLAY")
    setFont(div, 12, "")
    div:SetPoint("TOP", 0, -238)
    div:SetText("TABLES IN YOUR GROUP")
    div:SetTextColor(1, 1, 1)

    local lineL = home:CreateTexture(nil, "ARTWORK")
    lineL:SetPoint("RIGHT", div, "LEFT", -10, 0)
    lineL:SetPoint("LEFT", home, "LEFT", 16, 0)
    lineL:SetHeight(1)
    lineL:SetColorTexture(0.165, 0.176, 0.212, 1)
    local lineR = home:CreateTexture(nil, "ARTWORK")
    lineR:SetPoint("LEFT", div, "RIGHT", 10, 0)
    lineR:SetPoint("RIGHT", home, "RIGHT", -16, 0)
    lineR:SetHeight(1)
    lineR:SetColorTexture(0.165, 0.176, 0.212, 1)

    self.rows = {}
    for i = 1, MAX_ROWS do
        local row = UI.CreatePanel(home, WIDTH - 32, 54)
        row:SetPoint("TOP", 0, -258 - (i - 1) * 60)
        row:SetBackdropColor(0.055, 0.063, 0.082, 0.94)
        row:SetBackdropBorderColor(0.230, 0.247, 0.290, 1)

        row.dot = row:CreateTexture(nil, "OVERLAY")
        row.dot:SetSize(8, 8)
        row.dot:SetPoint("LEFT", 12, 0)
        row.dot:SetTexture("Interface\\Buttons\\WHITE8x8")

        row.name = row:CreateFontString(nil, "OVERLAY")
        setFont(row.name, 14, "")
        row.name:SetPoint("TOPLEFT", 30, -10)
        row.name:SetTextColor(unpack(C.GOLD))

        row.meta = row:CreateFontString(nil, "OVERLAY")
        setFont(row.meta, 12, "")
        row.meta:SetPoint("BOTTOMLEFT", 30, 10)
        row.meta:SetTextColor(unpack(C.TURQUOISE))

        row.joinBtn = UI.CreateBlueButton(row, 158, 34, "Join")
        row.joinBtn:SetPoint("RIGHT", -10, 0)
        setFont(row.joinBtn.label, 12, "")
        row.joinBtn:SetScript("OnClick", function()
            KH.Sounds:Play("UI_CLICK")
            if not row.hostName then return end
            if row.isFull then
                KH:Print("That table is full. Spectating comes later.")
                return
            end
            row.joinBtn.label:SetText("Joining...")
            KH.Comms:Whisper(row.hostName, KH.Comms.MSG.JOIN_REQUEST, row.tableId)
        end)

        row:Hide()
        self.rows[i] = row
    end

    local empty = home:CreateFontString(nil, "OVERLAY")
    setFont(empty, 12, "")
    empty:SetPoint("TOP", 0, -278)
    empty:SetWidth(WIDTH - 60)
    empty:SetText("No tables found in your group.\nHost one, or ask your party to open Komo Hold'Em.")
    empty:SetTextColor(0.65, 0.67, 0.71)
    self.empty = empty
end

-- ============================================================
-- LOBBY VIEW (hosting)
-- ============================================================
function Launcher:BuildLobby(f)
    local lobby = CreateFrame("Frame", nil, f)
    lobby:SetPoint("TOPLEFT", 0, -35)
    lobby:SetPoint("BOTTOMRIGHT", 0, 35)
    lobby:Hide()
    self.lobbyView = lobby

    local title = lobby:CreateFontString(nil, "OVERLAY")
    setFont(title, 18, "")
    title:SetPoint("TOP", 0, -16)
    title:SetTextColor(1, 1, 1)
    self.lobbyTitle = title

    -- ready counter pill
    local pill = UI.CreatePill(lobby, 190, 26)
    pill:SetPoint("TOP", 0, -44)
    setFont(pill.text, 12, "")
    self.readyPill = pill

    -- seat rows
    self.seatRows = {}
    for i = 1, MAX_SEATS do
        local row = UI.CreatePanel(lobby, WIDTH - 32, 40)
        row:SetPoint("TOP", 0, -84 - (i - 1) * 46)

        row.dot = row:CreateTexture(nil, "OVERLAY")
        row.dot:SetSize(8, 8)
        row.dot:SetPoint("LEFT", 12, 0)
        row.dot:SetTexture("Interface\\Buttons\\WHITE8x8")

        row.name = row:CreateFontString(nil, "OVERLAY")
        setFont(row.name, 13, "")
        row.name:SetPoint("LEFT", 30, 0)

        row.tag = row:CreateFontString(nil, "OVERLAY")
        setFont(row.tag, 10, "")
        row.tag:SetPoint("RIGHT", -12, 0)

        row:Hide()
        self.seatRows[i] = row
    end

    -- waiting note
    local note = lobby:CreateFontString(nil, "OVERLAY")
    setFont(note, 12, "")
    note:SetPoint("BOTTOM", 0, 116)
    note:SetTextColor(unpack(C.TURQUOISE))
    note:SetText("Waiting for players to join...")
    self.lobbyNote = note

    -- gold disclaimer (joiner side)
    local gnote = UI.CreatePanel(lobby, WIDTH - 32, 52)
    gnote:SetPoint("BOTTOM", 0, 138)
    gnote:SetBackdropColor(0.13, 0.10, 0.03, 0.92)
    gnote:SetBackdropBorderColor(0.847, 0.631, 0.227, 0.8)
    gnote.text = gnote:CreateFontString(nil, "OVERLAY")
    setFont(gnote.text, 11, "")
    gnote.text:SetPoint("TOPLEFT", 10, -8)
    gnote.text:SetPoint("BOTTOMRIGHT", -10, 8)
    gnote.text:SetJustifyH("LEFT")
    gnote.text:SetJustifyV("TOP")
    gnote:Hide()
    self.lobbyGoldNote = gnote

    -- start game (green when live, slate when locked)
    local start = CreateFrame("Button", nil, lobby, "BackdropTemplate")
    start:SetSize(WIDTH - 32, 42)
    start:SetPoint("BOTTOM", 0, 58)
    start:SetBackdrop(UI.BACKDROP)
    start:SetBackdropBorderColor(0.30, 0.32, 0.38, 1)
    start.label = start:CreateFontString(nil, "OVERLAY")
    setFont(start.label, 14, "")
    start.label:SetPoint("CENTER")
    self.startBtn = start

    start:SetScript("OnClick", function()
        if not start.enabled then return end
        KH.Host:StartGame()
    end)

    -- cancel (host)
    local cancel = UI.CreateRedButton(lobby, WIDTH - 32, 36, "Cancel Table")
    cancel:SetPoint("BOTTOM", 0, 12)
    setFont(cancel.label, 13, "")
    cancel:SetScript("OnClick", function()
        KH.Lobby:CloseTable()
        Launcher:ShowHome()
    end)
    self.cancelBtn = cancel

    -- ready toggle (joiner)
    local ready = CreateFrame("Button", nil, lobby, "BackdropTemplate")
    ready:SetSize(WIDTH - 32, 42)
    ready:SetPoint("BOTTOM", 0, 58)
    ready:SetBackdrop(UI.BACKDROP)
    ready.label = ready:CreateFontString(nil, "OVERLAY")
    setFont(ready.label, 14, "")
    ready.label:SetPoint("CENTER")
    ready:SetScript("OnClick", function()
        Launcher.myReady = not Launcher.myReady
        KH.Client:SetReady(Launcher.myReady)
        Launcher:PaintReadyButton()
    end)
    ready:Hide()
    self.readyBtn = ready

    -- leave (joiner)
    local leave = UI.CreateRedButton(lobby, WIDTH - 32, 36, "Leave Table")
    leave:SetPoint("BOTTOM", 0, 12)
    setFont(leave.label, 13, "")
    leave:SetScript("OnClick", function()
        KH.Client:LeaveTable()
    end)
    leave:Hide()
    self.leaveBtn = leave
end

-- ============================================================
-- view switching + rendering
-- ============================================================
function Launcher:Toggle()
    local f = self:Create()
    if f:IsShown() then f:Hide() else self:Show() end
end

function Launcher:Show(view)
    local f = self:Create()
    f:Show()
    if KH.Lobby.mine then self:ShowLobby()
    elseif view == "host" then self:ShowConfig()
    else self:ShowHome() end
    KH.Sounds:Play("UI_CLICK")
end

function Launcher:HideAllViews()
    if self.homeView then self.homeView:Hide() end
    if self.configView then self.configView:Hide() end
    if self.lobbyView then self.lobbyView:Hide() end
    if self.settleView then self.settleView:Hide() end
    if self.backBtn then self.backBtn:Hide() end
end

function Launcher:ShowHome()
    self:Create()
    self:HideAllViews()
    self.frame:SetHeight(HEIGHT)
    self.homeView:Show()
    self:RefreshTableList()
end

function Launcher:ShowLobby()
    self:Create()
    self:HideAllViews()
    self.lobbyView:Show()
    self:RefreshLobby()
end

function Launcher:RefreshTableList()
    if not self.frame or not self.homeView:IsShown() then return end
    local list = {}
    for _, t in pairs(KH.Lobby.known) do list[#list + 1] = t end
    table.sort(list, function(a, b) return a.name < b.name end)

    for i, row in ipairs(self.rows) do
        local t = list[i]
        if t then
            local open = t.seats - t.taken
            row.tableId = t.id
            row.hostName = t.host
            row.isFull = open <= 0
            row.name:SetText(t.name .. (t.stakes == "gold" and "  |cfffad990[GOLD]|r" or ""))
            row.meta:SetText(t.inProgress and ("Hand #" .. (t.handNo or "?") .. " in progress")
                                          or "Waiting for players")
            if open <= 0 then
                row.dot:SetVertexColor(0.847, 0.271, 0.227)
                row.joinBtn.label:SetText("|cffffffffFULL|r Spectate")
            else
                row.dot:SetVertexColor(0.310, 0.682, 0.420)
                local color = open >= 3 and "|cff7fd99a" or open == 2 and "|cffe8d06a" or "|cfff08a80"
                row.joinBtn.label:SetText("|cffffffffJOIN|r " .. color .. open ..
                    " Seat" .. (open == 1 and "" or "s") .. " Remaining|r")
            end
            row:Show()
        else
            row:Hide()
        end
    end
    if #list == 0 then self.empty:Show() else self.empty:Hide() end
end

function Launcher:PaintReadyButton()
    local b = self.readyBtn
    if not b then return end
    if self.myReady then
        b:SetBackdropColor(0.086, 0.137, 0.259, 1)
        b:SetBackdropBorderColor(0.227, 0.435, 0.784, 1)
        b.label:SetText("Unready")
        b.label:SetTextColor(0.490, 0.706, 0.941)
    else
        b:SetBackdropColor(0.239, 0.620, 0.388, 1)
        b:SetBackdropBorderColor(0.180, 0.490, 0.298, 1)
        b.label:SetText("Ready")
        b.label:SetTextColor(1, 1, 1)
    end
end

function Launcher:ShowJoinLobby()
    self.myReady = false
    self:ShowLobby()
end

function Launcher:RefreshLobby()
    local isHost = KH.Lobby.mine ~= nil
    local v = KH.Client.view
    local cfg = isHost and KH.Lobby.mine.config or (v and v.config)
    if not cfg then self:ShowHome() return end

    self.lobbyTitle:SetText(cfg.name or "Table")

    self.startBtn:SetShown(isHost)
    self.cancelBtn:SetShown(isHost)
    self.readyBtn:SetShown(not isHost)
    self.leaveBtn:SetShown(not isHost)

    if not isHost and cfg.stakes == "gold" then
        self.lobbyGoldNote.text:SetText(
            "|cfff6dd85Real WoW gold table — " .. (cfg.amount or "?") ..
            "g buy-in.|r |cffe8c96aIf you lose, you owe the gold you lost. Readying up means you accept these stakes.|r")
        self.lobbyGoldNote:Show()
    else
        self.lobbyGoldNote:Hide()
    end

    local roster, count = {}, 0
    if v and v.seats and v.count then
        for ix = 1, v.count do roster[ix] = v.seats[ix] end
        count = v.count
    elseif isHost then
        local t = KH.Lobby.mine
        for ix, name in ipairs(t.seatOrder) do
            local p = t.players[name]
            roster[ix] = { name = name, ready = p.ready, stack = p.stack }
        end
        count = #t.seatOrder
    end

    local seated, ready = count, 0
    for _, p in ipairs(roster) do
        if p.ready then ready = ready + 1 end
    end
    if not isHost then
        for _, p in ipairs(roster) do
            if KH:IsMe(p.name) then self.myReady = p.ready end
        end
    end
    if not isHost then self:PaintReadyButton() end

    self.readyPill.text:SetText("|cfffad990" .. ready .. "|r |cffffffffof|r |cfffad990" ..
        seated .. "|r |cffffffffPlayers Ready|r")

    local maxSeats = cfg.seats or 6
    local goldShown = (not isHost) and cfg.stakes == "gold"
    self.frame:SetHeight(math.max(500, 300 + maxSeats * 46 + (goldShown and 80 or 0)))
    local hostName = isHost and KH.playerFull or (v and v.host)

    for i = 1, MAX_SEATS do
        local row = self.seatRows[i]
        local p = roster[i]
        if p then
            local short = Ambiguate(p.name, "short")
            local isMe = KH:IsMe(p.name)
            local isHostRow = p.name == hostName
            if isHostRow then
                row:SetBackdropColor(0.910, 0.760, 0.400, 1)
                row:SetBackdropBorderColor(0.722, 0.537, 0.165, 1)
                row.name:SetText(short .. (isMe and " (You)" or ""))
                row.name:SetTextColor(0.09, 0.075, 0.04)
                row.tag:SetText("HOST")
                row.tag:SetTextColor(0.09, 0.075, 0.04)
            elseif isMe then
                row:SetBackdropColor(0.20, 0.14, 0.36, 0.96)
                row:SetBackdropBorderColor(0.482, 0.361, 0.941, 1)
                row.name:SetText(short .. " (You)")
                row.name:SetTextColor(1, 1, 1)
                row.tag:SetText(p.ready and "READY" or "Not ready")
                row.tag:SetTextColor(unpack(p.ready and C.GREEN or C.TEXT_DIM))
            else
                row:SetBackdropColor(0.098, 0.106, 0.129, 1)
                row:SetBackdropBorderColor(0.230, 0.247, 0.290, 1)
                row.name:SetText(short)
                row.name:SetTextColor(unpack(C.TEXT_DIM))
                row.tag:SetText(p.ready and "READY" or "Not ready")
                row.tag:SetTextColor(unpack(p.ready and C.GREEN or C.TEXT_DIM))
            end
            row.dot:SetVertexColor(p.ready and 0.498 or 0.541, p.ready and 0.851 or 0.565, p.ready and 0.604 or 0.612)
            row:Show()
        elseif i <= maxSeats then
            row:SetBackdropColor(0.055, 0.063, 0.082, 0.6)
            row:SetBackdropBorderColor(0.230, 0.247, 0.290, 0.7)
            row.name:SetText("Open seat")
            row.name:SetTextColor(0.5, 0.52, 0.56)
            row.tag:SetText("")
            row.dot:SetVertexColor(0.25, 0.27, 0.3)
            row:Show()
        else
            row:Hide()
        end
    end

    self.lobbyNote:SetShown(maxSeats <= 6 and not self.lobbyGoldNote:IsShown())

    if isHost then
        local t = KH.Lobby.mine
        local can = KH.Game:CanStart(t)
        local start = self.startBtn
        start.enabled = can
        if can then
            start:SetBackdropColor(0.239, 0.620, 0.388, 1)
            start.label:SetText("Start Game")
            start.label:SetTextColor(1, 1, 1)
            self.lobbyNote:SetText("All players ready!")
        else
            start:SetBackdropColor(0.149, 0.165, 0.200, 1)
            start.label:SetTextColor(0.43, 0.45, 0.50)
            if seated < 2 then
                start.label:SetText("Start Game — need 1 more player")
                self.lobbyNote:SetText("Waiting for players to join...")
            else
                start.label:SetText("Waiting for " .. (seated - ready) .. " player" ..
                    ((seated - ready) == 1 and "" or "s") .. " to ready up")
                self.lobbyNote:SetText("Waiting for players to ready up...")
            end
        end
    else
        self.lobbyNote:SetText(ready == seated and seated >= 2
            and "All players ready — waiting for host to start..."
            or "Waiting for players to ready up...")
    end
end

-- ============================================================
-- SETTLE VIEW
-- ============================================================
function Launcher:BuildSettle(f)
    if self.settleView then return end
    local sv = CreateFrame("Frame", nil, f)
    sv:SetPoint("TOPLEFT", 0, -35)
    sv:SetPoint("BOTTOMRIGHT", 0, 35)
    sv:Hide()
    self.settleView = sv

    local title = sv:CreateFontString(nil, "OVERLAY")
    setFont(title, 18, "")
    title:SetPoint("TOP", 0, -12)
    title:SetText("Table Closed")
    title:SetTextColor(1, 1, 1)

    local sum = UI.CreatePill(sv, 300, 26)
    sum:SetPoint("TOP", 0, -40)
    setFont(sum.text, 12, "")
    self.settleSummary = sum

    self.standRows = {}
    for i = 1, 8 do
        local row = UI.CreatePanel(sv, WIDTH - 32, 34)
        row:SetPoint("TOP", 0, -78 - (i - 1) * 38)
        row:SetBackdropColor(0.055, 0.063, 0.082, 0.94)
        row:SetBackdropBorderColor(0.230, 0.247, 0.290, 1)
        row.name = row:CreateFontString(nil, "OVERLAY")
        setFont(row.name, 13, "")
        row.name:SetPoint("LEFT", 12, 0)
        row.net = row:CreateFontString(nil, "OVERLAY")
        setFont(row.net, 13, "")
        row.net:SetPoint("RIGHT", -12, 0)
        row:Hide()
        self.standRows[i] = row
    end

    self.transRows = {}
    for i = 1, 6 do
        local row = UI.CreatePanel(sv, WIDTH - 32, 34)
        row:SetBackdropColor(0.165, 0.176, 0.212, 1)
        row:SetBackdropBorderColor(0.290, 0.310, 0.353, 1)
        row.text = row:CreateFontString(nil, "OVERLAY")
        setFont(row.text, 12, "")
        row.text:SetPoint("LEFT", 12, 0)
        row.paidBtn = UI.CreateBlueButton(row, 84, 24, "Mark Paid")
        row.paidBtn:SetPoint("RIGHT", -8, 0)
        setFont(row.paidBtn.label, 11, "")
        row:Hide()
        self.transRows[i] = row
    end

    local done = UI.CreateGoldButton(sv, WIDTH - 32, 40, "Done")
    done:SetPoint("BOTTOM", 0, 12)
    setFont(done.label, 14, "")
    done.label:SetTextColor(0.09, 0.075, 0.04)
    done:SetScript("OnClick", function() Launcher:ShowHome() end)
end

function Launcher:ShowSettle(view, results, transfers, hands)
    local f = self:Create()
    f:Show()
    self:BuildSettle(f)
    self:HideAllViews()
    self.settleView:Show()

    local nStand, nTrans = 0, 0
    for _ in pairs(results) do nStand = nStand + 1 end
    if transfers then nTrans = #transfers end
    f:SetHeight(math.max(480, 236 + nStand * 38 + nTrans * 38 + (nTrans > 0 and 16 or 0)))

    local isGold = view.config and view.config.stakes == "gold"
    local unit = isGold and "g" or ""
    self.settleSummary.text:SetText(
        (isGold and "|cffe8c96aWoW Gold table|r" or "|cff7db4f0Imitation Chips|r") ..
        " |cffffffff·|r |cffe8c96a" .. (view.config and view.config.amount or "?") ..
        (isGold and "g buy-in" or " chips") ..
        "|r |cffffffff·|r |cffe8c96a" .. (hands or 0) .. " hands|r")

    -- standings sorted by net
    local list = {}
    for name, net in pairs(results) do list[#list + 1] = { name = name, net = net } end
    table.sort(list, function(a, b) return a.net > b.net end)
    for i, row in ipairs(self.standRows) do
        local r = list[i]
        if r then
            local isMe = KH:IsMe(r.name)
            row.name:SetText(Ambiguate(r.name, "short") .. (isMe and " (You)" or ""))
            row.name:SetTextColor(1, 1, 1)
            if r.net >= 0 then
                row.net:SetText("|cff7fd99a+" .. BreakUpLargeNumbers(r.net) .. unit .. "|r")
            else
                row.net:SetText("|cfff08a80−" .. BreakUpLargeNumbers(-r.net) .. unit .. "|r")
            end
            row:Show()
        else
            row:Hide()
        end
    end

    -- transfers below standings (gold only)
    local baseY = -78 - #list * 38 - 8
    for i, row in ipairs(self.transRows) do
        local tr = transfers and transfers[i]
        if tr then
            row:ClearAllPoints()
            row:SetPoint("TOP", 0, baseY - (i - 1) * 38)
            row.text:SetText("|cffffffff" .. Ambiguate(tr.from, "short") ..
                " owes " .. Ambiguate(tr.to, "short") .. "|r  |cfffad990" ..
                BreakUpLargeNumbers(tr.amt) .. "g|r")
            row.paidBtn.label:SetText("Mark Paid")
            row.paidBtn:SetScript("OnClick", function()
                tr.paid = true
                KH.Ledger:MarkPaid(view.id, tr.from, tr.to)
                row.paidBtn.label:SetText("|cff7fd99aPAID|r")
                row:SetBackdropBorderColor(0.239, 0.620, 0.388, 1)
            end)
            row:SetBackdropBorderColor(0.290, 0.310, 0.353, 1)
            row:Show()
        else
            row:Hide()
        end
    end
end
