import type { Plugin } from 'vue'
import type { CreateBagelI18nOptions } from '../i18n'

import type { BagelToastOptions } from './useToast'
import { configure } from '@bagelink/utils'
import FloatingVue from 'floating-vue'
import lightboxPlugin from '../components/lightbox/index'
import { ripple, pattern } from '../directives'
import { createI18n, getI18n } from '../i18n'
import clickOutside from '../utils/clickOutside'
import { ModalPlugin } from './useModal'
import { ToastPlugin } from './useToast'
import '@oddbird/popover-polyfill'

export interface BagelOptions {
	/** i18n configuration options */
	i18n?: CreateBagelI18nOptions
	toast?: BagelToastOptions
}

export const BagelVue: Plugin<BagelOptions> = {
	install: (app, options = {}) => {
		// Install directives
		app.directive('click-outside', clickOutside)
		app.directive('ripple', ripple)
		app.directive('pattern', pattern)

		// Install UI plugins
		app.use(lightboxPlugin)
		app.use(ModalPlugin)
		app.use(ToastPlugin, options.toast || {})

		// Install FloatingVue for tooltips/popovers
		app.use(FloatingVue, {
			themes: {
				'bgl-theme': {
					triggers: ['click'],
					autoHide: true,
					placement: 'bottom',
				},
			},
		})

		// Setup i18n
		const i18n = createI18n(options.i18n || {})
		app.use(i18n as any)

		// Bridge locale into @bagelink/utils
		configure({
			locale: () => {
				try {
					const { locale } = getI18n().global
					return typeof locale === 'string' ? locale : locale.value
				} catch {
					return 'en'
				}
			},
		})
	},
}

// Re-export getI18n for advanced usage
export { getI18n }
