local obj = {}

-- Helper to handle the UI automation for creating and pasting into a new page
local function createAndPaste(content)
    hs.alert.show("Sending to AFFiNE...", 1.5)
    
    -- 1. Open/Focus the AFFiNE Desktop App
    hs.urlevent.openURL("affine://")
    
    -- 2. Wait for the app to come to the front and settle
    hs.timer.doAfter(1.2, function()
        local affine = hs.application.get("AFFiNE")
        if affine then
            affine:activate()
            
            -- Create a new page (Cmd+N)
            hs.eventtap.keyStroke({"cmd"}, "n")
            hs.timer.usleep(1000000) -- Wait 1s for the editor to load
            
            -- Move from Title to Body (Return)
            hs.eventtap.keyStroke({}, "return")
            hs.timer.usleep(500000)
            
            -- Set the clipboard to our note and paste (Cmd+V)
            hs.pasteboard.setContents(content)
            hs.timer.usleep(300000)
            hs.eventtap.keyStroke({"cmd"}, "v")
            
            hs.alert.show("Note Created ✅", 1.5)
        else
            hs.alert.show("AFFiNE App not found! ❌", 3)
        end
    end)
end

-- Function to get multi-line text input
local function getNoteInput()
    local script = [[
        tell application "System Events"
            activate
            set prompt to "Enter your quick note:"
            set theResponse to display dialog prompt default answer " " with title "AFFiNE Quick Note" buttons {"Cancel", "Send"} default button "Send"
            return text returned of theResponse
        end tell
    ]]
    
    local ok, result = hs.applescript(script)
    if ok and result and result ~= "" then
        createAndPaste(result)
    end
end

function obj.init()
    if not hyper then return end

    -- 1. Hyper + N: Manual text input dialog
    hs.hotkey.bind(hyper, "N", function()
        getNoteInput()
    end)
    
    -- 2. Hyper + V: Instantly send current clipboard contents to a new page
    hs.hotkey.bind(hyper, "V", function()
        local clipboard = hs.pasteboard.getContents()
        if clipboard and clipboard ~= "" then
            createAndPaste(clipboard)
        else
            hs.alert.show("Clipboard is empty!")
        end
    end)
end

return obj