-- Rack & Ruin: Lucky7.lua
-- Roll two dice, bet on whether the total lands Under 7, Exactly 7, or Over 7.
-- Same model as Roulette: the host rolls (so everyone agrees on the result),
-- but chip totals and bet resolution are handled locally per client - no
-- hidden information here, so no need for host-validated state syncing.

RackAndRuin = RackAndRuin or {}

local ORANGE = { 1, 0.55, 0.1 }
local GAME_ID = "LUCKY7"
local STARTING_CHIPS = 500

local frame = CreateFrame("Frame", "RackAndRuinLucky7Frame", UIParent, "BackdropTemplate")
frame:SetSize(600, 480)
frame:SetPoint("CENTER")
frame:SetMovable(true)
frame:EnableMouse(true)
frame:RegisterForDrag("LeftButton")
frame:SetScript("OnDragStart", frame.StartMoving)
frame:SetScript("OnDragStop", frame.StopMovingOrSizing)
frame:SetBackdrop({
    bgFile = "Interface\\Buttons\\WHITE8x8",
    edgeFile = "Interface\\Buttons\\WHITE8x8",
    edgeSize = 2,
})
frame:SetBackdropColor(0, 0, 0, 0.97)
frame:SetBackdropBorderColor(unpack(ORANGE))
frame:Hide()
RackAndRuin.RegisterManagedFrame(frame)

local statusText = frame:CreateFontString(nil, "OVERLAY", "GameFontNormalLarge")
statusText:SetPoint("TOP", 0, -28)
statusText:SetTextColor(1, 0.85, 0.2)
statusText:SetText("")

local chipsText = frame:CreateFontString(nil, "OVERLAY", "GameFontNormalLarge")
chipsText:SetPoint("TOPLEFT", 36, -60)
chipsText:SetTextColor(1, 1, 1)

local tableText = frame:CreateFontString(nil, "OVERLAY", "GameFontNormal")
tableText:SetPoint("TOPLEFT", 36, -92)
tableText:SetWidth(120)
tableText:SetJustifyH("LEFT")
tableText:SetJustifyV("TOP")
tableText:SetTextColor(0.7, 0.7, 0.7)
tableText:SetText("")

-- ============================================================
-- Dice display (plain text - no dice art assets needed)
-- ============================================================
local dieOneText = frame:CreateFontString(nil, "OVERLAY", "GameFontNormalHuge")
dieOneText:SetPoint("TOP", -60, -110)
dieOneText:SetText("-")

local plusText = frame:CreateFontString(nil, "OVERLAY", "GameFontNormalHuge")
plusText:SetPoint("TOP", 0, -110)
plusText:SetText("+")
plusText:SetTextColor(0.6, 0.6, 0.6)

local dieTwoText = frame:CreateFontString(nil, "OVERLAY", "GameFontNormalHuge")
dieTwoText:SetPoint("TOP", 60, -110)
dieTwoText:SetText("-")

local totalText = frame:CreateFontString(nil, "OVERLAY", "GameFontNormalHuge")
totalText:SetPoint("TOP", 0, -160)
totalText:SetText("")
totalText:SetTextColor(unpack(ORANGE))

-- ============================================================
-- Bet type selection
-- ============================================================
local BET_TYPES = {
    { id = "UNDER", label = "Under 7 (2-6)",  payout = 1 },
    { id = "SEVEN", label = "Exactly 7",      payout = 4 },
    { id = "OVER",  label = "Over 7 (8-12)",  payout = 1 },
}

local function StyledButton(parent, text, width, height)
    local btn = CreateFrame("Button", nil, parent, "BackdropTemplate")
    btn:SetSize(width or 170, height or 40)
    btn:SetBackdrop({
        bgFile = "Interface\\Buttons\\WHITE8x8",
        edgeFile = "Interface\\Buttons\\WHITE8x8",
        edgeSize = 2,
    })
    btn:SetBackdropColor(0, 0, 0, 1)
    btn:SetBackdropBorderColor(unpack(ORANGE))

    local label = btn:CreateFontString(nil, "OVERLAY", "GameFontNormal")
    label:SetPoint("CENTER")
    label:SetText(text)
    label:SetTextColor(1, 0.85, 0.6)
    btn.label = label

    btn:SetScript("OnEnter", function(self) if not self.selected then self:SetBackdropColor(0.2, 0.1, 0, 1) end end)
    btn:SetScript("OnLeave", function(self) if not self.selected then self:SetBackdropColor(0, 0, 0, 1) end end)

    return btn
end

local betButtons = {}
local selectedBet = nil

local function ClearBetVisuals()
    for _, btn in pairs(betButtons) do
        btn.selected = false
        btn:SetBackdropColor(0, 0, 0, 1)
    end
end

for i, bet in ipairs(BET_TYPES) do
    local btn = StyledButton(frame, bet.label .. "  (" .. bet.payout .. ":1)", 170, 40)
    btn:SetPoint("TOPLEFT", 36 + (i - 1) * 180, -200)
    btn:SetScript("OnClick", function()
        ClearBetVisuals()
        selectedBet = bet.id
        btn.selected = true
        btn:SetBackdropColor(0.35, 0.15, 0, 1)
    end)
    betButtons[bet.id] = btn
end

-- Wager amount
local wager = 10
local wagerText = frame:CreateFontString(nil, "OVERLAY", "GameFontNormalLarge")
wagerText:SetPoint("TOPLEFT", 36, -260)
wagerText:SetTextColor(1, 1, 1)

local function UpdateWagerText()
    wagerText:SetText("Wager: " .. wager .. " chips")
end
UpdateWagerText()

local function WagerButton(text, delta)
    local btn = StyledButton(frame, text, 60, 30)
    btn:SetScript("OnClick", function()
        wager = math.max(10, wager + delta)
        UpdateWagerText()
    end)
    return btn
end

local wagerMinus = WagerButton("-10", -10)
wagerMinus:SetPoint("LEFT", wagerText, "RIGHT", 16, 0)
local wagerPlus = WagerButton("+10", 10)
wagerPlus:SetPoint("LEFT", wagerMinus, "RIGHT", 8, 0)

-- ============================================================
-- Buttons: Roll / Back to Menu
-- ============================================================
local rollButton = StyledButton(frame, "Roll", 170, 42)
rollButton:SetPoint("BOTTOM", frame, "BOTTOM", -95, 30)

local backButton = StyledButton(frame, "Back to Menu", 170, 42)
backButton:SetPoint("LEFT", rollButton, "RIGHT", 16, 0)
backButton:SetScript("OnClick", function()
    frame:Hide()
    RackAndRuin.ShowMenu()
end)

-- ============================================================
-- Chip tracking - shared, session-persistent via RackAndRuin.Chips
-- ============================================================
local myName = UnitName("player")

local function UpdateChipsText()
    chipsText:SetText(myName .. ": " .. RackAndRuin.Chips.Get(myName) .. " chips")
end

local function ResolveBet(total)
    if not selectedBet then
        statusText:SetText("No bet placed - chips unchanged.")
        return
    end

    local betInfo
    for _, b in ipairs(BET_TYPES) do
        if b.id == selectedBet then betInfo = b end
    end

    local won = false
    if selectedBet == "UNDER" and total < 7 then won = true
    elseif selectedBet == "OVER" and total > 7 then won = true
    elseif selectedBet == "SEVEN" and total == 7 then won = true
    end

    if won then
        local payout = wager * betInfo.payout
        RackAndRuin.Chips.Add(myName, payout)
        statusText:SetText("You win " .. payout .. " chips!")
    else
        RackAndRuin.Chips.Add(myName, -wager)
        statusText:SetText("No win this roll.")
    end
    UpdateChipsText()
end

local function ShowRollResult(d1, d2)
    dieOneText:SetText(tostring(d1))
    dieTwoText:SetText(tostring(d2))
    local total = d1 + d2
    totalText:SetText("Total: " .. total)

    if total == 7 then
        totalText:SetTextColor(1, 0.85, 0.2)
    elseif total < 7 then
        totalText:SetTextColor(0.4, 0.8, 1)
    else
        totalText:SetTextColor(1, 0.5, 0.3)
    end

    ResolveBet(total)
end

-- ============================================================
-- Host roll + network wiring
-- ============================================================
local function HostRoll()
    local d1 = math.random(1, 6)
    local d2 = math.random(1, 6)
    RackAndRuin.Net.Send(GAME_ID, "RESULT", d1 .. "," .. d2)
    ShowRollResult(d1, d2)
end

RackAndRuin.Net.RegisterHandler(GAME_ID, "RESULT", function(sender, payload)
    if not RackAndRuin.Net.IsHost() then
        local d1, d2 = string.match(payload, "^(%d+),(%d+)$")
        if d1 then ShowRollResult(tonumber(d1), tonumber(d2)) end
    end
end)

rollButton:SetScript("OnClick", function()
    if not selectedBet then
        statusText:SetText("Pick a bet before rolling.")
        return
    end
    if wager > RackAndRuin.Chips.Get(myName) then
        statusText:SetText("Not enough chips for that wager.")
        return
    end

    if RackAndRuin.Net.IsHost() then
        HostRoll()
    else
        RackAndRuin.Net.Send(GAME_ID, "REQUESTROLL", "")
    end
end)

-- Non-host players can ask the host to roll (e.g. once everyone's bet is placed)
RackAndRuin.Net.RegisterHandler(GAME_ID, "REQUESTROLL", function(sender, payload)
    if RackAndRuin.Net.IsHost() then
        HostRoll()
    end
end)

-- ============================================================
-- Show/reset
-- ============================================================
function RackAndRuin.ShowLucky7()
    frame:Show()
    wager = 10
    selectedBet = nil
    ClearBetVisuals()
    UpdateChipsText()
    UpdateWagerText()
    dieOneText:SetText("-")
    dieTwoText:SetText("-")
    totalText:SetText("")
    statusText:SetText("Place your bet, then Roll.")

    local others = {}
    for _, name in ipairs(RackAndRuin.Net.GetPlayers()) do
        if name ~= myName then table.insert(others, name) end
    end
    if #others > 0 then
        tableText:SetText("At the table:\n" .. table.concat(others, "\n"))
    else
        tableText:SetText("")
    end

    if RackAndRuin.Net.IsGrouped() and not RackAndRuin.Net.IsHost() then
        rollButton.label:SetText("Ready to Roll")
    else
        rollButton.label:SetText("Roll")
    end
end

RackAndRuin.Lucky7Frame = frame
