import { parseCssClassList } from '@/utils/form-styles/classParser'

export interface FormStyleSelectors {
  formSelector: string
  wrapperSelector: string
  customClassName: string
  customClass: string
  baseSelector: string
}

export function normalizeFormScopeToken(formId: string | number): string {
  const normalized = String(formId)
    .trim()
    .replace(/[^a-zA-Z0-9_-]+/g, '-')
    .replace(/-+/g, '-')
    .replace(/^-|-$/g, '')

  return normalized || 'default'
}

export function buildFormPopperScopeClass(formId: string | number): string {
  return `ivyforms-form-popper-${normalizeFormScopeToken(formId)}`
}

export function buildFormStyleSelectors(
  formId: string | number,
  customCssClass?: string,
): FormStyleSelectors {
  const normalizedFormId = normalizeFormScopeToken(formId)
  const formSelector = `.ivyforms-form-${normalizedFormId}`
  const wrapperSelector = `.ivyforms-form-wrapper-${normalizedFormId}`
  const customClassName = parseCssClassList(customCssClass)[0] || ''
  const customClass = customClassName ? `.${customClassName}` : ''
  const baseSelector = customClass ? `${wrapperSelector}${customClass}` : wrapperSelector

  return {
    formSelector,
    wrapperSelector,
    customClassName,
    customClass,
    baseSelector,
  }
}
