# AlertDialog — accessible headless non-dismissable modal
#
# A Dialog variant that requires explicit user action to close.
# Cannot be dismissed by clicking outside or pressing Escape.
# Use for destructive confirmations, unsaved changes, etc.
# Ships zero CSS.
#
# Usage:
#   AlertDialog open <=> showConfirm
#     h2 "Delete account?"
#     p "This action cannot be undone."
#     button @click: (=> showConfirm = false), "Cancel"
#     button @click: handleDelete, "Delete"

export AlertDialog = component
  @open:: boolean := false
  @initialFocus:: any := null

  _prevFocus = null
  _id =! "adlg-#{Math.random().toString(36).slice(2, 8)}"

  ~>
    ARIA.bindDialog @open, (=> @_dialog), ((isOpen) =>
      if not isOpen and @open
        @open = false
        @emit 'close'
    ), false

  ~>
    if @open
      _prevFocus = document.activeElement
      ARIA.lockScroll(this)
      requestAnimationFrame =>
        panel = @_dialog
        if panel
          ARIA.wireAria panel, _id
          panel.setAttribute 'role', 'alertdialog'
          if @initialFocus
            target = if typeof @initialFocus is 'string' then panel.querySelector(@initialFocus) else @initialFocus
            target?.focus()
          else
            panel.querySelectorAll('a[href],button:not([disabled]),input:not([disabled]),select:not([disabled]),textarea:not([disabled]),[tabindex]:not([tabindex="-1"])')?[0]?.focus()
      return ->
        ARIA.unlockScroll(this)
        _prevFocus?.focus()

  close: ->
    @open = false
    @emit 'close'

  render
    dialog ref: "_dialog", $open: @open?!
      slot
