-- calling.lua - In-call screen functionality
-- Handles call state, duration timer, and call controls

local calling_doc = nil
local call_state = "connecting"  -- connecting, active, ended
local call_start_time = 0
local call_duration = 0
local timer_id = nil
local is_muted = false
local is_speaker = false
local is_on_hold = false

-- Call info
local call_number = ""
local call_name = ""

-- Initialize calling screen
function initCalling(doc)
    print("[Calling] Initializing...")
    calling_doc = doc

    -- Get call info from state or use defaults
    if mosis and mosis.state then
        local call_info = mosis.state.get("current_call")
        if call_info then
            call_number = call_info.number or ""
            call_name = call_info.name or call_number
        end
    end

    -- Fallback test data
    if call_number == "" then
        call_number = "+1 555-0101"
        call_name = "Alice Johnson"
    end

    -- Update UI
    updateCallInfo()

    -- Simulate connection after delay
    if setTimeout then
        setTimeout(function()
            setCallState("active")
        end, 2000)
    else
        setCallState("active")
    end
end

-- Update call info display
function updateCallInfo()
    if not calling_doc then return end

    local name_el = calling_doc:GetElementById("call-name")
    local number_el = calling_doc:GetElementById("call-number")
    local status_el = calling_doc:GetElementById("call-status")
    local avatar_el = calling_doc:GetElementById("call-avatar")

    if name_el then
        name_el.inner_rml = call_name
    end

    if number_el then
        number_el.inner_rml = call_number
    end

    if avatar_el then
        -- Get first letter for avatar
        local initial = call_name:sub(1, 1):upper()
        avatar_el.inner_rml = initial
    end
end

-- Set call state
function setCallState(state)
    print("[Calling] State changed to: " .. state)
    call_state = state

    local status_el = calling_doc:GetElementById("call-status")
    local timer_el = calling_doc:GetElementById("call-timer")

    if state == "connecting" then
        if status_el then
            status_el.inner_rml = "Calling..."
        end
        if timer_el then
            timer_el.style.display = "none"
        end
    elseif state == "active" then
        if status_el then
            status_el.inner_rml = "Connected"
        end
        if timer_el then
            timer_el.style.display = "block"
        end
        -- Start duration timer
        startCallTimer()
    elseif state == "ended" then
        if status_el then
            status_el.inner_rml = "Call ended"
        end
        stopCallTimer()
        -- Return to dialer after delay
        if setTimeout then
            setTimeout(function()
                if goBack then
                    goBack()
                end
            end, 1500)
        end
    end
end

-- Start call duration timer
function startCallTimer()
    call_start_time = os.time and os.time() or 0
    call_duration = 0

    if setInterval then
        timer_id = setInterval(function()
            call_duration = call_duration + 1
            updateTimerDisplay()
        end, 1000)
    end
end

-- Stop call timer
function stopCallTimer()
    if timer_id and clearInterval then
        clearInterval(timer_id)
        timer_id = nil
    end
end

-- Update timer display
function updateTimerDisplay()
    local timer_el = calling_doc:GetElementById("call-timer")
    if timer_el then
        local minutes = math.floor(call_duration / 60)
        local seconds = call_duration % 60
        timer_el.inner_rml = string.format("%02d:%02d", minutes, seconds)
    end
end

-- Toggle mute
function toggleMute()
    is_muted = not is_muted
    print("[Calling] Mute: " .. tostring(is_muted))

    local mute_btn = calling_doc:GetElementById("btn-mute")
    if mute_btn then
        if is_muted then
            mute_btn:SetClass("active", true)
        else
            mute_btn:SetClass("active", false)
        end
    end

    if showToast then
        showToast(is_muted and "Muted" or "Unmuted")
    end
end

-- Toggle speaker
function toggleSpeaker()
    is_speaker = not is_speaker
    print("[Calling] Speaker: " .. tostring(is_speaker))

    local speaker_btn = calling_doc:GetElementById("btn-speaker")
    if speaker_btn then
        if is_speaker then
            speaker_btn:SetClass("active", true)
        else
            speaker_btn:SetClass("active", false)
        end
    end

    if showToast then
        showToast(is_speaker and "Speaker on" or "Speaker off")
    end
end

-- Toggle hold
function toggleHold()
    is_on_hold = not is_on_hold
    print("[Calling] Hold: " .. tostring(is_on_hold))

    local hold_btn = calling_doc:GetElementById("btn-hold")
    if hold_btn then
        if is_on_hold then
            hold_btn:SetClass("active", true)
        else
            hold_btn:SetClass("active", false)
        end
    end

    local status_el = calling_doc:GetElementById("call-status")
    if status_el then
        if is_on_hold then
            status_el.inner_rml = "On hold"
        else
            status_el.inner_rml = "Connected"
        end
    end
end

-- Show dialpad
function showDialpad()
    print("[Calling] Show dialpad")
    if showToast then
        showToast("Dialpad")
    end
end

-- Add call (conference)
function addCall()
    print("[Calling] Add call")
    if showToast then
        showToast("Add call")
    end
end

-- End call
function endCall()
    print("[Calling] Ending call")
    setCallState("ended")
end
