import { html, LitElement, nothing, type TemplateResult } from 'lit'
import maplibregl from 'maplibre-gl'
import app from '../store/app.ts'
import { IMAGE_OPEN_EVENT } from './m-lightbox.ts'
import { icon } from '../utils/icon.ts'

export class MBookmarkViewPopup extends LitElement {
  bookmarkId = ''
  displayName = ''

  protected override createRenderRoot() {
    return this
  }

  /** Thumbnails ride the service worker's blob proxy — see `withBlobProxy`. */
  #thumbUrls(): string[] {
    if (!this.bookmarkId) return []
    const bookmark = app.bookmarks.find((b) => b.id === this.bookmarkId)
    return (bookmark?.images ?? [])
      .map((ref) => `/blob/${encodeURIComponent(ref.hash)}`)
  }

  #onThumbClick(url: string) {
    this.dispatchEvent(
      new CustomEvent(IMAGE_OPEN_EVENT, {
        bubbles: true,
        composed: true,
        detail: { url },
      }),
    )
  }

  #isFavorite(): boolean {
    if (!this.bookmarkId) return false
    return app.bookmarks.find((b) => b.id === this.bookmarkId)?.favorite ??
      false
  }

  override render(): TemplateResult {
    return html`
      <div class="bm-popup">
        <strong>
          ${this.displayName} ${this.#isFavorite()
            ? html`
              <span class="bm-favorite-badge" title="Favorite">${icon(
                'heart',
                '0.9em',
              )}</span>
            `
            : nothing}
        </strong>
        ${this.#thumbUrls().length
          ? html`
            <div class="bm-popup-thumbs">
              ${this.#thumbUrls().map((url) =>
                html`
                  <img
                    class="bm-popup-thumb"
                    src="${url}"
                    @click="${() => this.#onThumbClick(url)}"
                  />
                `
              )}
            </div>
          `
          : nothing} ${this.bookmarkId
          ? html`
            <a
              class="bm-popup-link"
              href="#!/bookmark/${encodeURIComponent(this.bookmarkId)}"
            >View details</a>
          `
          : nothing}
      </div>
    `
  }
}

customElements.define('m-bookmark-view-popup', MBookmarkViewPopup)

export type BookmarkViewPopupOptions = {
  bookmarkId?: string
  displayName: string
}

export function createBookmarkViewPopup(
  opts: BookmarkViewPopupOptions,
): maplibregl.Popup {
  const el = document.createElement(
    'm-bookmark-view-popup',
  ) as MBookmarkViewPopup
  el.bookmarkId = opts.bookmarkId ?? ''
  el.displayName = opts.displayName
  return new maplibregl.Popup({ offset: 10 }).setDOMContent(el)
}
