-- Layout System for Virtual Smartphone
-- Provides reusable UI component helpers
-- Requires navigation.lua to be loaded first

-- Icon paths (relative to assets/)
local ICON_PATH = "../../icons/"

-- Default icons
local icons = {
    back = ICON_PATH .. "back.tga",
    home = ICON_PATH .. "home.tga",
    menu = ICON_PATH .. "menu.tga",
    search = ICON_PATH .. "search.tga",
    more = ICON_PATH .. "more.tga",
    close = ICON_PATH .. "close.tga",
    wifi = ICON_PATH .. "wifi.tga",
    signal = ICON_PATH .. "signal.tga",
    battery = ICON_PATH .. "battery.tga"
}

-- Get current time formatted as HH:MM
local function getCurrentTime()
    -- In sandbox, we might not have os.date, use a default
    if os and os.date then
        return os.date("%H:%M")
    end
    return "12:30"
end

-- Update status bar time
function updateStatusTime(doc)
    local timeEl = doc:GetElementById("status-time")
    if timeEl then
        timeEl.inner_rml = getCurrentTime()
    end
end

-- Initialize status bar with current time
-- Call from document onload
function initStatusBar(doc)
    updateStatusTime(doc)

    -- Set up timer to update time every minute if timers are available
    if setTimeout then
        local function updateLoop()
            updateStatusTime(doc)
            setTimeout(updateLoop, 60000)
        end
        setTimeout(updateLoop, 60000)
    end
end

-- Initialize app bar back button
-- Call from document onload
function initAppBar(doc)
    local backBtn = doc:GetElementById("app-bar-back")
    if backBtn then
        -- Back button is handled via onclick in RML
        -- This is for any additional setup
    end
end

-- Initialize system navigation bar
-- Call from document onload
function initSystemNav(doc)
    -- Navigation buttons are handled via onclick in RML
    -- This is for any additional setup
end

-- Full layout initialization
-- Call from document onload: initLayout(document)
function initLayout(doc)
    initStatusBar(doc)
    initAppBar(doc)
    initSystemNav(doc)
    print("Layout initialized")
end

-- Handle back button press (for app bar or system nav)
function onBackPressed()
    if canGoBack and canGoBack() then
        goBack()
    else
        -- If at root, go home
        if goHome then
            goHome()
        end
    end
end

-- Handle home button press
function onHomePressed()
    if goHome then
        goHome()
    end
end

-- Handle recent apps button press (placeholder)
function onRecentPressed()
    print("Recent apps pressed (not implemented)")
end

print("Layout system loaded")
