import { html, LitElement, type TemplateResult } from 'lit'

/** Opens the app-wide lightbox; `detail` carries the image URL. */
export const IMAGE_OPEN_EVENT = 'bookmark-image-open'

/**
 * The app's single full-bleed image viewer. Mounted once in index.html
 * (outside `main`, so it also survives the share-view boot path); anything
 * can open it by dispatching a bubbling {@link IMAGE_OPEN_EVENT} with
 * `{ detail: { url } }`, so pages and popups don't each carry their own
 * dialog copy.
 */
export class MLightbox extends LitElement {
  #url: string | null = null

  protected override createRenderRoot() {
    return this
  }

  override connectedCallback() {
    super.connectedCallback()
    document.addEventListener(IMAGE_OPEN_EVENT, this.#onOpen)
  }

  override disconnectedCallback() {
    super.disconnectedCallback()
    document.removeEventListener(IMAGE_OPEN_EVENT, this.#onOpen)
  }

  #onOpen = (e: Event) => {
    this.#url = (e as CustomEvent<{ url: string }>).detail.url
    this.requestUpdate()
  }

  #close = () => {
    this.#url = null
    this.requestUpdate()
  }

  override render(): TemplateResult {
    return html`
      <ui-dialog ?open="${this.#url !== null}" @dismiss="${this.#close}">
        <dialog>
          <article class="bm-lightbox">
            <img src="${this.#url ?? ''}" alt="" @click="${this.#close}">
          </article>
        </dialog>
      </ui-dialog>
    `
  }
}

customElements.define('m-lightbox', MLightbox)
