import './app.css'
import App from './App.svelte'
import { getRecaptchaKey } from './services/ConfigService'

const targets = getWidgetTargets()

if (!targets.length) {
  throw new Error('No se ha encontrado el contenedor del botón Ticketary.')
}

const apps = targets.map(target => new App({
  target,
  props: getWidgetProps(target),
}))

export default apps

addRecaptchaScript(getRecaptchaKey())

function getWidgetTargets() {
  const widgets = Array.from(document.querySelectorAll<HTMLElement>('[data-ticketary-widget]'))
  const appTarget = document.getElementById('app')

  if (widgets.length) {
    return widgets
  }

  return appTarget ? [appTarget] : []
}

function addRecaptchaScript(key: string) {
  if (!key || document.querySelector(`script[src*="recaptcha/api.js?render=${key}"]`)) {
    return
  }

  const script = document.createElement('script')
  script.src = `https://www.google.com/recaptcha/api.js?render=${key}`
  document.body.append(script)
}

function getWidgetProps(target: HTMLElement) {
  const params = new URLSearchParams(window.location.search)
  const dataset = target?.dataset ?? {}

  return {
    accountId: dataset.accountId || params.get('accountId') || undefined,
    sessionId: dataset.sessionId || params.get('sessionId') || undefined,
    activityId: dataset.activityId || params.get('activityId') || undefined,
    productType: dataset.productType || params.get('productType') || undefined,
    buttonText: dataset.buttonText || undefined,
    days: Number.parseInt(dataset.days || params.get('days') || '30', 10),
  }
}
