local isTableViewerOpen = false
local currentTableData = nil
local resourceVersion = GetResourceMetadata(GetCurrentResourceName(), 'version', 0) or '1.0.0'

---@param table any The table to be viewed
---@param title string Optional title for the table view
---@return boolean Success status
local function viewTable(table, title)
    if type(table) ~= "table" then
        print("bs-tableviewer: Input is not a table")
        return false
    end
    
    local success, result = pcall(function()
        return json.encode(table)
    end)
    
    if not success then
        print("bs-tableviewer: Failed to encode table to JSON")
        return false
    end
    
    currentTableData = result
    isTableViewerOpen = true
    
    SendNUIMessage({
        action = 'openTableViewer',
        data = result,
        title = title,
        version = resourceVersion
    })
    
    SetNuiFocus(true, true)
    return true
end

RegisterNUICallback('closeTableViewer', function(_, cb)
    isTableViewerOpen = false
    SetNuiFocus(false, false)
    currentTableData = nil
    cb('ok')
end)

exports('debugTable', viewTable)

RegisterCommand('testviewer', function()
    local testTable = {
        name = "Test Table",
        nested = {
            value = 123,
            array = {1, 2, 3, 4, 5},
            deep = {
                deeper = {
                    deepest = "Hello World"
                }
            }
        },
        array = {"a", "b", "c"},
        boolean = true,
        number = 42
    }

    viewTable(testTable, "Test Table Viewer")
end, false)

RegisterNetEvent('debugTable')
AddEventHandler('debugTable', function(tableData, title)
    viewTable(tableData, title)
end)