////
// Links can be #command (will run in the prompt) or real links, which run in 
// a NOSE browser so you always stay in the UI's safe embrace.

import { runCommand } from "./shell"
import { focusInput } from "./focus"
import { openBrowser, isBrowsing } from "./browser"

export function initHyperlink() {
  window.addEventListener("click", handleClick)
}

async function handleClick(e: MouseEvent) {
  const target = e.target

  if (!(target instanceof HTMLElement)) return

  const a = target.closest("a")
  if (!a) return

  const href = a.getAttribute("href")
  if (!href) return

  if (href.startsWith("#") && href.length > 1) {
    e.preventDefault()
    await runCommand(href.slice(1))
    focusInput()
  } else if (!isBrowsing() && !e.metaKey) {
    e.preventDefault()
    openBrowser(href)
  }
}