require "CreditCardLayouts"
require "ISUI/ISCollapsableWindow"

CreditCardUI = ISCollapsableWindow:derive("CreditCardUI")

function CreditCardUI:new(x, y, width, height, item)
    local o = ISCollapsableWindow.new(self, x, y, width, height)

    o.title = ""
    o.resizable = false
    o.drawFrame = false

    o.backgroundColor = {r=0, g=0, b=0, a=0}
    o.borderColor     = {r=0, g=0, b=0, a=0}

    -- Load card data (includes design)
    o.data = CreditCardData:new(item)

    -- Apply stored design
    local layoutId = o.data.design or "Default"
    o.layout = CreditCardLayouts[layoutId] or CreditCardLayouts.Default

    o.texturePath = o.layout.background
    o.fontPath    = o.layout.font.path
    o.fontScale   = o.layout.font.scale

    -- Card content
    o.fullname = o.data.firstname .. " " .. o.data.lastname

    if o.data.signatureTexture then
        o.signatureTexture = getTexture(o.data.signatureTexture)
    end

    if o.data.logoTexture then
        o.logoTexture = getTexture(o.data.logoTexture)
    end

    if o.data.blooded and o.data.bloodTexture then
        o.bloodTexture = getTexture(o.data.bloodTexture)
    end

    print("[CreditCardUI] new() → layout:", layoutId)

    return o
end

--------------------------------------------------
-- Initialise (load textures ONCE)
--------------------------------------------------
function CreditCardUI:initialise()
    ISCollapsableWindow.initialise(self)

    self.bitmapFont = {}

    local chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-'"

    for i = 1, #chars do
        local c = chars:sub(i, i)
        local tex = getTexture(self.fontPath .. c .. ".png")
        if tex then
            self.bitmapFont[c] = tex
        else
            print("[CreditCardUI] Missing font texture for:", c)
        end
    end

    print("[CreditCardUI] Bitmap font loaded")
end

--------------------------------------------------
-- Bitmap text renderer
--------------------------------------------------
function CreditCardUI:drawBitmapText(text, startX, startY, letterSpacing)
    if not text then return end
    if not self.bitmapFont then return end

    local x = startX
    text = string.upper(tostring(text))

    local gap = letterSpacing

    for i = 1, #text do
        local char = text:sub(i, i)

        if char == " " then
            x = x + 50
        else
            local tex = self.bitmapFont[char]
            if tex then
                local w = tex:getWidth() * self.fontScale
                local h = tex:getHeight() * self.fontScale

                -- 🔴 DEBUG: show where the letter should be
                --self:drawRectBorder(x, startY, w, h, 1, 1, 0, 0)

                self:drawTextureScaled(tex, x, startY, w, h, 1, 1, 1, 1)

                x = x + w + gap
            else
                print("[CreditCardUI] No texture for char:", char)
                x = x + 10
            end
        end
    end
end


--------------------------------------------------
-- Render
--------------------------------------------------
function CreditCardUI:render()

    ISCollapsableWindow.render(self)
    self:renderBackground()

    local text = self.layout.text

    -- First & Last name
    self:drawBitmapText(
        self.fullname,
        text.fullname.x,
        text.fullname.y,
        text.fullname.gap
    )

    -- Card number
    self:drawBitmapText(
        self.data.cardNumber,
        text.cardNumber.x,
        text.cardNumber.y,
        text.cardNumber.gap
    )

    -- Expire date
    self:drawBitmapText(
        self.data.expireDate,
        text.expireDate.x,
        text.expireDate.y,
        text.expireDate.gap
    )

    -- Signature
    if self.layout.showSignature and self.signatureTexture and self.layout.signature then

        local s = self.layout.signature

        self:drawTextureScaled(
            self.signatureTexture,
            s.x, s.y, s.w, s.h,
            1.0
        )
    end

    -- Logo
    if self.layout.showLogo and self.logoTexture then
        self:drawTextureScaled(
            self.logoTexture,
            0, 0,
            self.width, self.height,
            1.0
        )
    end

    -- Blood overlay
    if self.data.blooded and self.bloodTexture then
        self:drawTextureScaled(
            self.bloodTexture,
            0, 0,
            self.width, self.height,
            1.0
        )
    end
    
end

function CreditCardUI:renderBackground()
    local tex = getTexture(self.texturePath)
    if tex then
        self:drawTexture(tex, 0, 0, 1.0)
    end
end

--------------------------------------------------
-- Close
--------------------------------------------------
function CreditCardUI:close()
    self.quitting = true
    ISCollapsableWindow.close(self)
end

--------------------------------------------------
-- UI Spawner
--------------------------------------------------
function ShowCreditCardUI(item)

    local w, h = 1024, 660

    local ui = CreditCardUI:new(
        (getCore():getScreenWidth() - w) / 2,
        (getCore():getScreenHeight() - h) / 2,
        w, h, item, "BlackCard"
    )
    ui:initialise()
    ui:addToUIManager()
    ui:setVisible(true)
    return ui
end
