import { createApp } from 'petite-vue'
import { l10nObj } from '@/helper'

import template from './template'
import wishlistPublicTemplatePro from '../public/wishlistPublicTemplatePro'
import wishlistMounted from './wishlist'

const loadedObject = l10nObj()
const proDependencies = loadedObject.proDependencies || {}
const activePro = proDependencies?.activePro || false

/**
 * Custom element for the wishlist app.
 */
class SavetoWishlist extends HTMLElement {
  // Reactive scope returned by `wishlistMounted()`; held so we can expose
  // selected methods (e.g. `refreshWishlist()`) on the host element for
  // sibling plugins like the registry extension to call.
  private scope: ReturnType<typeof wishlistMounted> | null = null

  constructor() {
    super()
  }

  connectedCallback() {
    // Create container with v-scope for the app.
    const container = document.createElement('div')
    container.setAttribute('id', 'saveto-wishlist-app')
    container.setAttribute('v-scope', '')
    container.innerHTML = template
    if ( activePro ) {
      container.insertAdjacentHTML('beforeend', wishlistPublicTemplatePro)
    }
    this.appendChild(container)

    this.scope = wishlistMounted()
    const app = createApp(this.scope)

    // Mount the app.
    app.mount(container)
  }

  /**
   * Public method: refetch wishlist items.
   *
   * Sibling plugins (e.g. the registry extension) can trigger a refresh via
   * `document.querySelector('stwlite-wishlist').refreshWishlist()` after they
   * mutate state that affects the lite table.
   */
  refreshWishlist(): unknown {
    return this.scope?.refreshWishlist?.()
  }
}

export default SavetoWishlist