-- Navigation System for Virtual Smartphone
-- Handles screen transitions and state management

-- Screen registry - maps screen names to RML file paths
local screens = {
    home = "apps/home/home.rml",
    lock = "apps/home/lock.rml",
    dialer = "apps/dialer/dialer.rml",
    calling = "apps/dialer/calling.rml",
    contacts = "apps/contacts/contacts.rml",
    contact_detail = "apps/contacts/contact_detail.rml",
    messages = "apps/messages/messages.rml",
    chat = "apps/messages/chat.rml",
    settings = "apps/settings/settings.rml",
    browser = "apps/browser/browser.rml",
    store = "apps/store/store.rml",
    camera = "apps/camera/camera.rml",
    music = "apps/music/music.rml"
}

-- Use global state to persist across document loads
-- Initialize only if not already set
if not _G.nav_state then
    _G.nav_state = {
        history = {},
        current_screen = "home",
        nav_direction = "none"  -- "forward", "back", "home", "none"
    }
end

-- Local references for convenience
local history = _G.nav_state.history
local function get_current() return _G.nav_state.current_screen end
local function set_current(s) _G.nav_state.current_screen = s end
local function get_direction() return _G.nav_state.nav_direction end
local function set_direction(d) _G.nav_state.nav_direction = d end

-- Apply animation class based on navigation direction
local function applyNavAnimation()
    local dir = get_direction()
    print("Applying animation, direction: " .. dir)
    if dir ~= "none" and document then
        -- In RmlUi Lua, get body element
        local body = document.body
        if body then
            print("Found body element, setting class nav-" .. dir)
            -- Set the appropriate animation class
            if dir == "forward" then
                body:SetClass("nav-forward", true)
            elseif dir == "back" then
                body:SetClass("nav-back", true)
            elseif dir == "home" then
                body:SetClass("nav-home", true)
            else
                body:SetClass("nav-default", true)
            end
        else
            print("Body element not found!")
        end
    end
end

-- Navigate to a screen by name
function navigateTo(screen_name)
    print("navigateTo called with: " .. tostring(screen_name))
    local path = screens[screen_name]
    if path then
        -- Push current screen to history before navigating
        table.insert(history, get_current())
        set_current(screen_name)
        set_direction("forward")

        -- Load the new screen using C++ function
        local success = loadScreen(path)
        if success then
            applyNavAnimation()
            print("Navigated to: " .. screen_name .. " (history depth: " .. #history .. ")")
        else
            -- Restore previous state on failure
            set_current(table.remove(history))
            print("Failed to navigate to: " .. screen_name)
        end
        return success
    else
        print("Unknown screen: " .. screen_name)
        return false
    end
end

-- Go back to previous screen
function goBack()
    print("goBack called (history depth: " .. #history .. ")")
    if #history > 0 then
        local previous = table.remove(history)
        local path = screens[previous]
        if path then
            set_current(previous)
            set_direction("back")
            loadScreen(path)
            applyNavAnimation()
            print("Back to: " .. previous)
            return true
        end
    else
        print("No history to go back to")
    end
    return false
end

-- Go to home screen (clear history)
function goHome()
    -- Clear the history table
    for i = #history, 1, -1 do
        history[i] = nil
    end
    set_current("home")
    set_direction("home")
    loadScreen(screens.home)
    applyNavAnimation()
    print("Navigated to home")
end

-- Get current screen name
function getCurrentScreen()
    return get_current()
end

-- Check if we can go back
function canGoBack()
    return #history > 0
end

-- Clear navigation history
function clearHistory()
    for i = #history, 1, -1 do
        history[i] = nil
    end
end

-- Get history depth
function getHistoryDepth()
    return #history
end

print("Navigation system initialized (current: " .. get_current() .. ", history: " .. #history .. ")")
