/**
 * Highlight a block by ID — scrolls it into view and plays a
 * gentle background-colour pulse that fades away.
 *
 * If the block element isn't in the DOM yet (e.g. the editor is still
 * rendering), polls at 50ms intervals until it appears.
 */
function waitForBlock(blockId: string, timeout = 5000): Promise<HTMLElement | null> {
  return new Promise((resolve) => {
    const selector = `[data-block-id="${blockId}"]`

    const el = document.querySelector<HTMLElement>(selector)
    if (el) return resolve(el)

    const start = Date.now()
    const interval = setInterval(() => {
      const found = document.querySelector<HTMLElement>(selector)
      if (found) {
        clearInterval(interval)
        resolve(found)
      } else if (Date.now() - start > timeout) {
        clearInterval(interval)
        resolve(null)
      }
    }, 50)
  })
}

export function useBlockHighlight() {
  async function highlight(blockId: string) {
    const el = await waitForBlock(blockId)
    if (!el) {
      console.warn("[highlight] block not found in DOM:", blockId)
      return
    }
    doHighlight(el)
  }

  return { highlight }
}

function doHighlight(el: HTMLElement) {
  el.scrollIntoView({ behavior: "smooth", block: "center" })

  // Let the smooth scroll settle before showing the flash
  setTimeout(() => {
    el.classList.add("block-highlight")
    setTimeout(() => el.classList.remove("block-highlight"), 1200)
  }, 400)
}
