-- camera.lua - Camera app functionality
-- Handles capture, modes, flash, zoom, and camera switching

local camera_doc = nil
local current_mode = "photo"  -- photo, video, portrait, night
local flash_mode = "auto"     -- auto, on, off
local timer_mode = "off"      -- off, 3, 10
local is_front_camera = false
local is_recording = false
local zoom_level = 1.0
local photo_count = 0
local video_duration = 0
local video_timer_id = nil

-- Camera modes
local modes = {"Night", "Portrait", "Photo", "Video", "More"}

-- Initialize camera
function initCamera(doc)
    print("[Camera] Initializing...")
    camera_doc = doc
    updateModeDisplay()
    updateFlashDisplay()
    updateTimerDisplay()
    updateZoomDisplay()
end

-- Update mode display
function updateModeDisplay()
    if not camera_doc then return end

    for _, mode in ipairs(modes) do
        local mode_el = camera_doc:GetElementById("mode-" .. mode:lower())
        if mode_el then
            if mode:lower() == current_mode then
                mode_el:SetClass("active", true)
            else
                mode_el:SetClass("active", false)
            end
        end
    end

    -- Update capture button appearance for video mode
    local capture_btn = camera_doc:GetElementById("capture-button")
    if capture_btn then
        if current_mode == "video" then
            if is_recording then
                capture_btn.inner_rml = [[<div class="capture-btn-stop"></div>]]
            else
                capture_btn.inner_rml = [[<div class="capture-btn-video"></div>]]
            end
        else
            capture_btn.inner_rml = [[<div class="capture-btn-inner"></div>]]
        end
    end
end

-- Switch camera mode
function switchMode(mode)
    print("[Camera] Switching to mode: " .. mode)
    current_mode = mode:lower()

    -- Stop recording if switching from video
    if is_recording then
        stopRecording()
    end

    updateModeDisplay()

    if showToast then
        showToast(mode .. " mode")
    end
end

-- Toggle flash
function toggleFlash()
    if flash_mode == "auto" then
        flash_mode = "on"
    elseif flash_mode == "on" then
        flash_mode = "off"
    else
        flash_mode = "auto"
    end

    print("[Camera] Flash: " .. flash_mode)
    updateFlashDisplay()
end

-- Update flash display
function updateFlashDisplay()
    if not camera_doc then return end

    local indicator = camera_doc:GetElementById("flash-indicator")
    if indicator then
        local text = "Flash: "
        if flash_mode == "auto" then
            text = text .. "Auto"
        elseif flash_mode == "on" then
            text = text .. "On"
        else
            text = text .. "Off"
        end
        indicator.inner_rml = text
    end
end

-- Toggle timer
function toggleTimer()
    if timer_mode == "off" then
        timer_mode = "3"
    elseif timer_mode == "3" then
        timer_mode = "10"
    else
        timer_mode = "off"
    end

    print("[Camera] Timer: " .. timer_mode)
    updateTimerDisplay()
end

-- Update timer display
function updateTimerDisplay()
    if not camera_doc then return end

    local indicator = camera_doc:GetElementById("timer-indicator")
    if indicator then
        local text = "Timer: "
        if timer_mode == "off" then
            text = text .. "Off"
        else
            text = text .. timer_mode .. "s"
        end
        indicator.inner_rml = text
    end
end

-- Zoom in
function zoomIn()
    if zoom_level < 10.0 then
        zoom_level = math.min(zoom_level + 0.5, 10.0)
        updateZoomDisplay()
    end
end

-- Zoom out
function zoomOut()
    if zoom_level > 0.5 then
        zoom_level = math.max(zoom_level - 0.5, 0.5)
        updateZoomDisplay()
    end
end

-- Update zoom display
function updateZoomDisplay()
    if not camera_doc then return end

    local indicator = camera_doc:GetElementById("zoom-level")
    if indicator then
        indicator.inner_rml = string.format("%.1fx", zoom_level)
    end

    print("[Camera] Zoom: " .. zoom_level)
end

-- Switch camera (front/back)
function switchCamera()
    is_front_camera = not is_front_camera
    print("[Camera] Switched to " .. (is_front_camera and "front" or "back") .. " camera")

    if showToast then
        showToast(is_front_camera and "Front camera" or "Back camera")
    end

    -- Update viewfinder placeholder
    local placeholder = camera_doc:GetElementById("viewfinder-placeholder")
    if placeholder then
        local icon = is_front_camera and "F" or "C"
        placeholder.inner_rml = [[
            <div class="viewfinder-placeholder-icon">]] .. icon .. [[</div>
            <div>]] .. (is_front_camera and "Front Camera" or "Camera Preview") .. [[</div>
            <div style="font-size: 14px; margin-top: 8px; color: #555555;">Tap to focus</div>
        ]]
    end
end

-- Capture photo or start/stop video
function capture()
    if current_mode == "video" then
        if is_recording then
            stopRecording()
        else
            startRecording()
        end
    else
        takePhoto()
    end
end

-- Take a photo
function takePhoto()
    print("[Camera] Taking photo...")

    -- Check timer
    if timer_mode ~= "off" then
        local delay = tonumber(timer_mode) * 1000
        if showToast then
            showToast("Timer: " .. timer_mode .. " seconds")
        end

        if setTimeout then
            setTimeout(function()
                actuallyTakePhoto()
            end, delay)
        else
            actuallyTakePhoto()
        end
    else
        actuallyTakePhoto()
    end
end

-- Actually capture the photo
function actuallyTakePhoto()
    photo_count = photo_count + 1
    print("[Camera] Photo captured! Total: " .. photo_count)

    -- Flash effect
    if flash_mode == "on" or (flash_mode == "auto" and not is_front_camera) then
        -- Simulate flash
    end

    -- Show capture animation/feedback
    local viewfinder = camera_doc:GetElementById("camera-viewfinder")
    if viewfinder then
        viewfinder.style["background-color"] = "#FFFFFF"
        if setTimeout then
            setTimeout(function()
                viewfinder.style["background-color"] = "#1a1a1a"
            end, 100)
        end
    end

    if showToast then
        showToast("Photo saved")
    end

    -- Update gallery preview
    updateGalleryPreview()
end

-- Start video recording
function startRecording()
    print("[Camera] Starting recording...")
    is_recording = true
    video_duration = 0

    updateModeDisplay()

    -- Start timer
    if setInterval then
        video_timer_id = setInterval(function()
            video_duration = video_duration + 1
            updateRecordingTime()
        end, 1000)
    end

    -- Show recording indicator
    local indicator = camera_doc:GetElementById("recording-indicator")
    if indicator then
        indicator.style.display = "flex"
    end
end

-- Stop video recording
function stopRecording()
    print("[Camera] Stopping recording...")
    is_recording = false

    -- Stop timer
    if video_timer_id and clearInterval then
        clearInterval(video_timer_id)
        video_timer_id = nil
    end

    updateModeDisplay()

    -- Hide recording indicator
    local indicator = camera_doc:GetElementById("recording-indicator")
    if indicator then
        indicator.style.display = "none"
    end

    if showToast then
        local minutes = math.floor(video_duration / 60)
        local seconds = video_duration % 60
        showToast(string.format("Video saved (%02d:%02d)", minutes, seconds))
    end

    video_duration = 0
end

-- Update recording time display
function updateRecordingTime()
    if not camera_doc then return end

    local time_el = camera_doc:GetElementById("recording-time")
    if time_el then
        local minutes = math.floor(video_duration / 60)
        local seconds = video_duration % 60
        time_el.inner_rml = string.format("%02d:%02d", minutes, seconds)
    end
end

-- Update gallery preview
function updateGalleryPreview()
    -- In a real app, this would show the last captured photo
    local preview = camera_doc:GetElementById("gallery-preview")
    if preview then
        preview.style["background-color"] = "#4CAF50"
    end
end

-- Open gallery
function openGallery()
    print("[Camera] Opening gallery...")
    if navigateTo then
        navigateTo("gallery")
    else
        if showToast then
            showToast("Gallery: " .. photo_count .. " photos")
        end
    end
end

-- Open camera settings
function openCameraSettings()
    print("[Camera] Opening settings...")
    if showToast then
        showToast("Camera settings")
    end
end

-- Handle tap to focus
function onViewfinderTap(x, y)
    print("[Camera] Focus at: " .. x .. ", " .. y)

    -- Move focus indicator
    local focus = camera_doc:GetElementById("focus-indicator")
    if focus then
        focus.style.left = x .. "px"
        focus.style.top = y .. "px"
        focus.style.opacity = "1"

        if setTimeout then
            setTimeout(function()
                focus.style.opacity = "0.8"
            end, 500)
        end
    end
end
