<template>
  <component
    :is="resolvedSettings"
    :form-component="GoogleSheetsForm"
    :list-component="GoogleSheetsList"
  />
</template>

<script setup lang="ts">
import { computed, type Component } from 'vue'
import GoogleSheetsSingleIntegrationSettings from './GoogleSheetsSingleIntegrationSettings.vue'
import GoogleSheetsForm from './components/GoogleSheetsForm.vue'
import GoogleSheetsList from './components/GoogleSheetsList.vue'

const HOOK = 'ivyforms/google_sheets/multi_settings_component'
const REGISTRY_KEY = 'GoogleSheetsMultiIntegrationSettings'
const FEATURE_SLUG = 'google_sheets_multi'

const isVueComponent = (value: unknown): value is Component =>
  !!value &&
  (typeof value === 'function' || typeof value === 'object') &&
  ('render' in (value as Record<string, unknown>) ||
    'setup' in (value as Record<string, unknown>) ||
    '__hmrId' in (value as Record<string, unknown>) ||
    '__name' in (value as Record<string, unknown>))

const hasMultiFeature = (): boolean => {
  try {
    return window.IvyForms?.hasProFeature?.(FEATURE_SLUG) === true
  } catch {
    return false
  }
}

const resolveMultiSettings = (): Component | null => {
  if (!hasMultiFeature()) {
    return null
  }

  const hooks = window.IvyForms?.hooks || window.IvyForms?.api?.hooks
  if (hooks?.applyFilters) {
    const fromHook = hooks.applyFilters<Component | null>(HOOK, null)
    if (isVueComponent(fromHook)) {
      return fromHook
    }
  }

  const fromRegistry = window.IvyForms?.components?.[REGISTRY_KEY]
  if (isVueComponent(fromRegistry)) {
    return fromRegistry
  }

  return null
}

const resolvedSettings = computed(() => {
  const hooks = window.IvyForms?.hooks || window.IvyForms?.api?.hooks
  void hooks?.updateCounter?.value

  return resolveMultiSettings() || GoogleSheetsSingleIntegrationSettings
})
</script>
