import { EditorView } from "@codemirror/view"
import { Todo } from "./todo"
import { triggerTodoCompletionEffect } from "./todoCompletion"

export const todoClickHandler = EditorView.domEventHandlers({
  click(event, view) {
    const element = event.target as HTMLElement
    const pos = view.posAtCoords({ x: event.clientX, y: event.clientY })
    if (pos === null) return false

    const line = view.state.doc.lineAt(pos)
    const todo = Todo.parse(line.text)

    if (!todo) return false

    if (element.matches(".todo-url")) {
      const url = element.getAttribute("data-url")
      if (url) {
        window.open(url, "_blank")
        return true
      }
    }

    if (element.matches(".todo-checkbox")) {
      todo.done = !todo.done
      if (todo.done) {
        triggerTodoCompletionEffect(view, line.from)
      }
      view.dispatch({
        changes: {
          from: line.from,
          to: line.to,
          insert: todo.toString(),
        },
      })
    }

    return false
  },
})
