export function mergeTailwindVariants(
  preset: any,
  override: any,
  level: number = 0,
  merge: boolean = true,
  compound: boolean = false
): any {
  let objects = typeof preset === 'object' ? 1 : 0
  objects += typeof override === 'object' ? 1 : 0

  if (!objects) {
    if (merge && typeof preset === 'string' && typeof override === 'string') {
      return `${preset} ${override}` // tailwind-variants uses tailwind-merge anyway if installed
    }

    return override == null ? preset : override
  }

  if (objects === 1) {
    return preset
  }

  const merged = { ...preset }

  for (const key in override) {
    if (key in preset) {
      merge = merge && (level > 0 || key !== 'defaultVariants')
      compound = compound || (level === 0 && key === 'compoundVariants')

      merged[key] = mergeTailwindVariants(
        preset[key],
        override[key],
        level + 1,
        compound ? key !== 'class' : merge,
        compound
      )
    }
  }

  if (level === 0 && 'base' in merged) {
    if (merged.base) {
      const slots = merged.slots ?? {}
      slots.base = `${slots.base ?? ''} ${merged.base}`
      merged.slots = slots
    }

    delete merged.base
  }

  return merged
}
