local obj = {}

local function getBrowserURL()
    local app = hs.application.frontmostApplication()
    local name = app:name()
    local script = ""
    if name == "Safari" then
        script = 'tell app "Safari" to return URL of front document'
    elseif name == "Google Chrome" or name == "Brave Browser" or name == "Microsoft Edge" then
        script = 'tell app "' .. name .. '" to return URL of active tab of front window'
    else
        return nil
    end
    local ok, url = hs.applescript(script)
    return ok and url or nil
end

function obj.clip()
    hs.timer.usleep(200000) 
    
    local url = getBrowserURL()
    hs.alert.show("Clipping to AFFiNE...", 1.5)
    
    hs.pasteboard.clearContents()
    hs.eventtap.keyStroke({"cmd"}, "c")
    hs.timer.usleep(800000)
    
    local clippedText = hs.pasteboard.getContents()
    
    if not clippedText or clippedText == "" then
        hs.alert.show("Nothing selected! ❌", 2)
        return
    end
    
    hs.urlevent.openURL("affine://")
    
    hs.timer.doAfter(1.2, function()
        local affine = hs.application.get("AFFiNE")
        if affine then
            affine:activate()
            hs.eventtap.keyStroke({"cmd"}, "n")
            hs.timer.usleep(1000000)
            
            hs.eventtap.keyStroke({}, "return")
            hs.timer.usleep(500000)
            
            if url then
                hs.pasteboard.setContents("Source: " .. url .. "\n\n")
                hs.timer.usleep(300000)
                hs.eventtap.keyStroke({"cmd"}, "v")
                hs.timer.usleep(800000)
            end
            
            hs.pasteboard.setContents(clippedText)
            hs.timer.usleep(300000)
            hs.eventtap.keyStroke({"cmd"}, "v")
            
            hs.alert.show("Clipped Successfully ✅", 1.5)
        else
            hs.alert.show("AFFiNE App not found! ❌", 3)
        end
    end)
end

function obj.init()
    -- Replaced the binding to use your Hyper Key + C
    hs.hotkey.bind(hyper, "C", function()
        obj.clip()
    end)
end

return obj